Learn Python – The argparse in Python- Basic and advance

In this article, we will examine the argparse module in Python. We will discover its working and functionalities. It is a very important theme for the crucial developer, engineer, and computer scientist. As we all familiar, Python is famous for containing and rich library. If the developer writes the script for the command line, he/she is also required to ignore the command-line argument that we can create the use of the argparse library.

In this article, we will discover the following topics associated to argparse.

What is the command-line interface?

What is argparse in Python?

How to implement Python argparse library to create a command-line interface?

Types of Arguments in Command-line Interface

Python argparse Positional Argument

Python argparse Positional Argument Default Values

Using a short name for Optional Arguments

Combining Optional and Positional Arguments with argparse

Conclusion

Let’s recognize what is argparse is and how we can enforce it.

What is command line interface?

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

How does the command line interface work?

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

C:\Users\DEVANSH SHARMA>ls  

Output:

face.png
Favorites
file1.txt
file2.txt
flower.jpg
forest.jpg
Gow-0.8.0.exe
gradients.jpg
hadoop-2.8.0
hadoop-2.8.0.tar.gz
hello_fullstack
highway.mp4
IBA_IOAPDATA
innocentcat
IntelGraphicsProfiles
international-cricket-players-data.zip
Iris.csv
iris.zip
java_error_in_pycharm_6408.log
java_error_in_pycharm_6684.log
jtp_logo.png
linear_reg
linear_reg.zip
Links
Local Settings
main_image.jpg
mario.png
metastore_db
MicrosoftEdgeBackups
Music
My Documents
mycus
9c409ba1dd3f}.TMContainer00000000000000000001.regtrans-ms
NTUSER.DAT{42939bbc-edb6-11ea-9c24-9c409ba1dd3f}.TMContainer00000000000000000002.regtrans-ms
ntuser.ini
PySpark DataFrame.ipynb
PySpark RDD.ipynb
PySpark SQL.ipynb
PySpark UDF.ipynb
tesseract-3.02.02-win32-lib-include-dirs
tesseract-3.02.02-win32-lib-include-dirs.zip

As we can see in the above output, the ls command returns many archives that are reachable in the modern-day directory.

Now, we will run the ls command by including option -l to the command line.

C:\Users\DEVANSH SHARMA>ls -l  

Output:

total 717704
drw-rw-rw-   2 DEVANSH SHARMA 0         0 2020-04-07 13:25 __pycache__
dr--r--r--   2 DEVANSH SHARMA 0         0 2020-09-03 13:42 3D Objects
drw-rw-rw-   2 DEVANSH SHARMA 0         0 2014-01-03 15:37 8235702-a50f7c449c41b6dc8eb87d8d393eeff62121b392
drw-rw-rw-  20 DEVANSH SHARMA 0     32768 2020-12-07 16:20 Anaconda3
drw-rw-rw-   5 DEVANSH SHARMA 0         0 2020-09-03 13:02 AppData
drw-rw-rw-   2 DEVANSH SHARMA 0      8192 2021-02-11 21:39 Application Data
-rw-rw-rw-   1 DEVANSH SHARMA 0       224 2019-11-13 14:38 array.mat
-rw-rw-rw-   1 DEVANSH SHARMA 0     69548 2019-12-03 14:18 ballon.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0     69548 2019-12-03 14:20 baloon.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0      1857 2019-10-15 12:16 binary.png
-rw-rw-rw-   1 DEVANSH SHARMA 0         5 2020-04-01 16:46 binfile.bin
-rw-rw-rw-   1 DEVANSH SHARMA 0     13911 2019-10-16 11:52 blob.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0    244879 2019-10-14 14:19 book1.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0     10064 2020-04-07 16:35 calculation.py
-rw-rw-rw-   1 DEVANSH SHARMA 0     23073 2019-12-06 15:30 calibresult.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0       336 2019-11-29 15:11 cat.jpeg
-rw-rw-rw-   1 DEVANSH SHARMA 0         0 2019-12-05 12:34 cat.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0     13001 2019-10-13 17:22 cat_16x9.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0    249726 2019-10-13 15:02 cat1.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0      5633 2019-12-04 11:16 coin.jpg
-rw-rw-rw-   1 DEVANSH SHARMA 0      8652 2019-12-04 11:23 coin1.png
-rw-rw-rw-   1 DEVANSH SHARMA 0     59918 2020-03-02 11:22 comic.png
dr--r--r--   2 DEVANSH SHARMA 0         0 2020-09-03 13:42 Contacts

What is argparse in Python?

Python argparse is a command-line parsing module that is advocated to work with the command line argument. This module used to be released as a part of the preferred library with Python on twentieth February 2011.

It is similar to the getopt module, but it is slightly difficult to use and requires extra code strains to perform the equal task. However, the argparse module is the higher replacement of the Python getopt and optparse module. It presents a few necessary facets that are given below.

It allows us to use to positional argument.

It allows us to customize the prefix chars.

It supports variable numbers of parameters for a single option.

It supports subcommands.

How to implement the argparse library to create a command-line interface?

Let’s see the following simple instance to understand the working of the argparse module in Python.

Example – In the following example, we create a simple Python program to function the add operation the use of the argparse module. We will pass the argument via 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 all through the program. We have called the add_argument() technique 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

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

When we press enter, it will exhibit the following output.

Output:

usage: code.py [-h] num1 num2 operation
code.py: error: the following arguments are required: num1, num2, operation

As we can see, it suggests error due to the fact we did not ignore the required argument.

Now, we will ignore the optionally available argument – h which is basically used for help.

Command

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

It will show the following output.

usage: code.py [-h] num1 num2 operation

positional arguments:
  num1        first number
  num2        second number
  operation   operation

optional arguments:
  -h, --help  show this help message and exit

We get all the arguments list which we have described in our Python program. Now, we will print each arguments and the operation by using including the following operation. When we execute the .parse_args(), we get a Namespace object containing a easy property of each input argument obtained from the command line.

args = parser.parse_args()  
  
print(args.num1)  
print(args.num2)  
print(args.operation)  

We print the argument to the console the usage of the args variable. By default, it takes enter 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)  
C:\Users\DEVANSH SHARMA\PycharmProjects\Elasticsearch>python code.py 20 30 add
20
30
add
The Result is :  50

Example – 1 Simple Calculator Program the use of 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.

Positional Argument

Optional Argument

Let’s understand the both arguments.

Positional Argument – Positional arguments are the sorts of argument that we use in command to operate. We pass by the argument to the command and function some operations. Their function defines via their function. That’s why they are known as a positional argument.

By default, the positional arguments are dealt with as String, alternatively we can typecast in different records types.

In the preceding example, we have used positional arguments to operate 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 exceeded 15 and it returned 1515 due to the fact argparse handled as string. We can right this using the kind 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 no longer get the error if now not exceeded to the script. These types of arguments are started with the – single sprint or “–” double sprint prefix. We want to call the .add_parse() to ignore the optionally available 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 besides 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 non-obligatory argument and instead of returning error it returns none. The assist message and facts types for optional parameters are same as in positional parameters.

Python argparse Positional Argument

Sometimes, we want the arguments that are obligatory to be exceeded in the script on execution. Let’s see an example it no longer passed.

Example –

import argparse  
  
parser = argparse.ArgumentParser()  
parser.add_argument("example")  
args = parser.parse_args()  
  
if args.example == 'Hello Python':  
    print('Welcome to Javatpoint')  
else:  
    print("Didn't make it!")  

When we run the above code with the distinct parameter, it will show the following argument.

Output:

We can exhibit the error if the argument is not handed in the command line terminal.

Python argparse Positional Argument Default Values

We can supply the default fee to a variable or argument the use of the argparse module. In the previous example, positional argument fee 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 Javatpoint')  
else:  
    print("Didn't make it!")  

Output:

Using Short Name for Optional Argument

Passing the many optionally available can make our Python script long. So we can assign the brief name to the parameters as well. We can provide the abbreviation identify to parameters; it will help us to maintain 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 == 'Javatpoint':  
    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 brief to each non-obligatory arguments. We can get right of entry to it via using its quick name.

Combining Optional and Positional Arguments with argparse

We can combine each optionally available and role arguments the use of the argparse as follows. Let’s apprehend 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 == 'Javatpoint':  
    print('You made it!')  
  
if args.writer == 'Devansh':  
    print('Technical Writer.')  

Output:

C:\Users\DEVANSH SHARMA\PycharmProjects\Elasticsearch>python code.py Javatpoint -w Devansh
You made it!
Technical Writer.

We have surpassed both kinds of argument to the command-line and get the above output.

Conclusion

So far, we have discussed all-important thought of the argparse Python module. We have discovered how we can create them and how we can use them through the command-line interface. We have also realized what the argparse module is and why it is necessary to write command-line scripts in Python.

This module helps us create self-explanatory programs and furnish customers with a capability of interacting with our application.