Tutorialspoint

1 Answer
Chandu yadav
, 0 Views

Very often we need to pass arguments to Python script when executing from command line. However, the script raises exception when parameters needed are not provided in equal number or type or order. That’s where the need to properly parse the command line argument occurs.

The argparse module provides tools for writing very easy to use command line interfaces. It handles how to parse the arguments collected in sys.argv list, automatically generate help and issues error message when invalid options are given.

First step to desing the command line interface is to set up parser object. This is done by ArgumentParser() function in argparse module. The function can be given an explanatory string as description parameter.

To start with our script will be executed from command line without any arguments. Still use parse_args() method of parser object, which does nothing because there aren’t any arguments given.

import argparse
parser = argparse.ArgumentParser(description="sample argument parser")
args=parser.parse_args()

When above script is run

C:\python36>python argparser1.py
C:\python36>python argparser1.py --help
usage: argparser1.py [-h]
sample argument parser
optional arguments:
-h, --help  show this help message and exit

The second command line usage gives –help option which produces a help message as shown. The –help parameter is available by default.

Now let us define an argument which is mandatory for the script to run and if not given script should throw error. Here we define argument ‘user’ by add_argument() method.

import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user")
args = parser.parse_args()
if args.user=="Admin":
   print ("Hello Admin")
else:
   print ("Hello Guest")

This script’s help now shows one positional argument in the form of ‘user’. The program checks if it’s value is ‘Admin’ or not and prints corresponding message.

C:\python36>python argparser1.py --help
usage: argparser1.py [-h] user
sample argument parser
positional arguments:
  user
optional arguments:
  -h, --help  show this help message and exit
C:\python36>python argparser1.py Admin
Hello Admin
C:\python36>python argparser1.py temp
Hello Guest

We can assign default value to an argument in add_argument() method.

import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user", nargs='?',default="Admin")
args=parser.parse_args()
if args.user=="Admin":
   print ("Hello Admin")
else:
   print ("Hello Guest")

Here nargs is the number of command-line arguments that should be consumed. '?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

C:\python36>python argparser1.py
Hello Admin
C:\python36>python argparser1.py Admin
Hello Admin
C:\python36>python argparser1.py test
Hello Guest

By default, all arguments are treated as strings. To explicitly mention type of argument, use type parameter in the add_argument() method. All Python data types are valid values of type.

import argparse
parser=argparse.ArgumentParser(description="add numbers")
parser.add_argument("first", type=int)
parser.add_argument("second", type=int)
args = parser.parse_args()
x = args.first
y = args.second
z = x+y
print ('addition of {} and {} = {}'.format(x,y,z))
C:\python36>python argparser2.py 2 3
addition of 2 and 3 = 5

In above examples, the arguments are mandatory. To add optional argument, prefix its name by double dash --. In following case surname argument is optional because it is prefixed by double dash (--surname)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--surname")
args = parser.parse_args()
print ("My name is ", args.name, end=' ')
if args.surname:
   print (args.surname)

A one letter name of argument prefixed by single dash acts as a short name option.

C:\python36>python argparser3.py Malhar
My name is  Malhar
C:\python36>python argparser3.py Malhar --surname Lathkar
My name is  Malhar Lathkar
parser.add_argument("-s","--surname")

If it is desired that an argument should value only from a defined list, it is defined as choices parameter.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("sub", choices=['Physics', 'Maths', 'Biology'])
args=parser.parse_args()
print ("My subject is ", args.sub)

Note that if value of parameter is not from the list, invalid choice error is displayed.

C:\python36>python argparser4.py Physics
My subject is  Physics
C:\python36>python argparser4.py English
usage: argparser4.py [-h] {Physics,Maths,Biology}
argparser4.py: error: argument sub: invalid choice: 'English' (choose from 'Physics', 'Maths', 'Biology')

Advertisements