The Argparse in Python
The Argparse in Python
As we can see in the above output, the ls command returns many files that are
available in the current directory.
Now, we will run the ls command by adding option -l to the command line.
What is argparse in Python?
Python argparse is a command-line parsing module that is recommended to work
with the command line argument. This module was released as a part of the standard
library with Python on 20th February 2011.
It is similar to the getopt module, but it is slightly hard to use and requires more
code lines to perform the same task. However, the argparse module is the better
replacement of the Python getopt and optparse module. It provides a few
important features that are given below.
parser = argparse.ArgumentParser()
To run this program, we open the command-line interface and run the above file.
Command
We get all the arguments list which we have defined in our Python program. Now, we
will print both arguments and the operation by adding the following operation.
When we execute the .parse_args(), we get a Namespace object containing a simple
property of each input argument received from the command line.
args = parser.parse_args()
print(args.num1)
print(args.num2)
print(args.operation)
We print the argument to the console using the args variable. By default, it takes
input as so we need to typecast into integer.
n1 = int(args.num1)
n2 = int(args.num2)
To add these two numbers, we define the add operation in our code.
result = n1 + n2
print("The Result is : ",result)
parser = argparse.ArgumentParser()
args = parser.parse_args()
print(args.num1)
print(args.num2)
print(args.operation)
n1 = int(args.num1)
n2 = int(args.num2)
if args.operation == "add":
result = n1 + n2
print("The Result is : ", result)
Output:
o Positional Argument
o Optional Argument
Positional Argument - Positional arguments are the types of argument that we use
in command to operate. We pass the argument to the command and perform some
operations. Their position defines by their function. That's why they are called a
positional argument.
By default, the positional arguments are treated as String, however we can typecast
in other data types.
In the previous example, we have used positional arguments to perform the add
operation between the two numbers.
Example - 1
import argparse
parser = argparse.ArgumentParser()
Output:
We have passed 15 and it returned 1515 because argparse treated as string. We can
correct this using the type attribute.
Example -
import argparse
parser = argparse.ArgumentParser()
Output:
Optional Argument - Optional Argument are not mandatory. We will not get the
error if not passed to the script. These types of arguments are started with the -
single dash or "--" double dash prefix. We need to call the .add_parse() to pass the
optional arguments.
Example -
parser = argparse.ArgumentParser()
args = parser.parse_args()
print(args.num1)
print(args.num2)
print(args.operation)
n1 = int(args.num1)
n2 = int(args.num2)
if args.operation == "add":
result = n1 + n2
print("The Result is : ", result)
When we run the above code without passing any arguments, it will show the
following output.
Output:
As we can see in the above code, we ran the script without passing any optional
argument and instead of returning error it returns none. The help message and data
types for optional parameters are same as in positional parameters.
Example -
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("example")
args = parser.parse_args()
When we run the above code with the different parameter, it will show the following
argument.
Output:
We can show the error if the argument is not passed in the command line terminal.
Example –
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("example", default="Hello How are you")
args = parser.parse_args()
if args.example == 'Hello':
print('Welcome to Learnmore')
else:
print("Didn't make it!")
Output:
Example -
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-tut', '--tutorial', help="Best Tutorial ")
parser.add_argument('-w', '--writer', help="Technical Content")
args = parser.parse_args()
if args.tutorial == "Learnmore":
print('Congratulation|| You made it!')
if args.writer == 'Devansh':
print('Technical Writer.')
Output:
In the above code, we have assigned the short to both optional arguments. We can
access it by using its short name.
Example –
import argparse
parser = argparse.ArgumentParser()
# positionl Argument
parser.add_argument('tutorial', help="Best Tutorial ")
# optional argument
parser.add_argument('-w', '--writer', help="Technical Content")
args = parser.parse_args()
if args.tutorial == "Learnmore":
print('You made it!')
if args.writer == 'Devansh':
print('Technical Writer.')
Output:
We have passed both types of argument to the command-line and get the above
output.