Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

The Argparse in Python

The document discusses the argparse module in Python which is used for parsing command line arguments. It explains what is command line interface, what argparse is, how to implement it to create command line interfaces, different types of arguments like positional and optional arguments and how to use them with argparse.

Uploaded by

Abhishek Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

The Argparse in Python

The document discusses the argparse module in Python which is used for parsing command line arguments. It explains what is command line interface, what argparse is, how to implement it to create command line interfaces, different types of arguments like positional and optional arguments and how to use them with argparse.

Uploaded by

Abhishek Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

The argparse in Python

o What is the command-line interface?


o What is argparse in Python?
o How to implement Python argparse library to create a command-line
interface?
o Types of Arguments in Command-line Interface
o Python argparse Positional Argument
o Python argparse Positional Argument Default Values
o Using a short name for Optional Arguments
o Combining Optional and Positional Arguments with argparse
o Conclusion

What is command line interface?


o The command-line interface is also known as the CLI, which interacts with a
command-line script. Python provides many libraries that allow us to work
with the CLI, but Python argparse is the most suitable library in the current
scenario.

How does the command line interface work?


Before getting deep down into this topic, we need to understand how the command
line interface works? So open the command line terminal and type
the ls command to get the entire list of files available in the system.

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.

o It allows us to use to positional argument.


o It allows us to customize the prefix chars.
o It supports variable numbers of parameters for a single option.
o It supports subcommands.

How to implement the argparse library to


create a command-line interface?
Let's see the following simple example to understand the working of the argparse
module in Python.

Example - In the following example, we create a simple Python program to perform


the add operation using the argparse module. We will pass the argument through
the command-line interface.

# importing argparse module


import argparse

parser = argparse.ArgumentParser()

# creating two variables using the add_argument method


parser.add_argument("num1", help="first number")
parser.add_argument("num2", help="second number")
parser.add_argument("operation", help="operation")
We have imported the argparse module and created a simple parser that will use
throughout the program. We have called the add_argument() method and pass two
arguments - num1 and help. We have saved the above code in the file
named code.py.

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)

Example - 1 Simple Calculator Program using argparse

# importing argparse module


import argparse

parser = argparse.ArgumentParser()

# creating two variables using the add_argument method


parser.add_argument("num1", help="first number")
parser.add_argument("num2", help="second number")
parser.add_argument("operation", help="operation")

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)

elif args.operation == "sub":


result = n1 - n2

elif args.operation == "mul":


result = n1 * n2
elif args.operation == "div":
result = n1 / n2
else:
print("Unmatched Argument")

print("result is : ", result)

Output:

Types of Argument in Command Line


Interface
There are two arguments that we can add to the command-line interface.

o Positional Argument
o Optional Argument

Let's understand the both arguments.

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.

Let's understand the following code.

Example - 1

import argparse

parser = argparse.ArgumentParser()

# By default, it treats input number as string


parser.add_argument('num', help="Enter nmber to get square of it.")
args = parser.parse_args()
print(args.num ** 2)

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()

parser.add_argument('num', help="Enter number to get square of it.",


type=int)
args = parser.parse_args()
print(args.num ** 2)

Output:

Now, we get the desired result.

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.

Let's understand the following example.

Example -

# importing argparse module


import argparse

parser = argparse.ArgumentParser()

# creating two variables using the add_argument method


parser.add_argument("--num1", help="first number")
parser.add_argument("--num2", help="second number")
parser.add_argument("--operation", help="operation")

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)

elif args.operation == "sub":


result = n1 - n2

elif args.operation == "mul":


result = n1 * n2
elif args.operation == "div":
result = n1 / n2
else:
print("Unmatched Argument")

print("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.

Python argparse Positional Argument


Sometimes, we need the arguments that are mandatory to be passed in the script on
execution. Let's see an example it not passed.

Example -

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("example")
args = parser.parse_args()

if args.example == 'Hello Python':


print('Welcome to Learnmore')
else:
print("Didn't make it!")

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.

Python argparse Positional Argument


Default Values
We can provide the default value to a variable or argument using the argparse
module. In the previous example, positional argument value is empty when not
provided. Let's understand the following example.

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:

Using Short Name for Optional Argument


Passing the many optional can make our Python script long. So we can assign the
short name to the parameters as well. We can give the abbreviation name to
parameters; it will help us to keep our Python script short.

Let's understand the following example.

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:

C:\Users\DEVANSH SHARMA\PycharmProjects\Elasticsearch>python code.py -w


Devansh
Technical Writer.

In the above code, we have assigned the short to both optional arguments. We can
access it by using its short name.

Combining Optional and Positional Arguments with


argparse
We can combine both optional and position arguments using the argparse as
follows. Let's understand the following example.

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:

C:\Users\DEVANSH SHARMA\PycharmProjects\Elasticsearch>python code.py


Learnmore -w Devansh
You made it!
Technical Writer.

We have passed both types of argument to the command-line and get the above
output.

You might also like