Do you like this page?



Views of this page
311

Views of the site
14824


Please help share my site. Thank you!







A Guide to Command Line Arguments with ArgParse in Python - Easy Microbial Genomics

A Guide to Command Line Arguments with ArgParse in Python

Last updated: April 25, 2022

You might have seen some Python programs that can show help message and accept options and arguments in command line running.

❤ That looks cool and you can write such programs after today's tutorial.

Install argparse

The module to use is the 'argparse'. Install it by 'pip install argparse'.

Getting started

Here is a small program to demonstrate the structure and usage of argparse.

import argparse
# Create a parser
parser = argparse.ArgumentParser()
# Add arguments
parser.add_argument('-n1', '--number1', dest='n1', required=True)
parser.add_argument('-n2', '--number2', dest='n2', required=True)
# Parse the arguments
args = parser.parse_args()
# Start programming
print('The two inputs are '+args.n1+' and '+args.n2)
sum = int(args.n1) + int(args.n2)
print('The sum is '+str(sum))

It first created a parser object, and then added arguments to it. You can specify the option names of the arguments, which appear in the command line behind a '-' or '--', like '-n1'. You can specify the destination of the argument so you can call it as an attribute of the parser later in the script. If it is a positional argument, you need to set the option 'required' as 'True'. Otherwise, it is an optional argument by default.

Save it as 'sum.py' and then run

sum.py -n1 5 -n2 8

Display description

Above is a simple demonstration showing how 'argparse' works. Now let's make it more powerful.

If you want to let users read a description of your program, you can add a brief tutorial in the help message.

Change the parser to

# Create a parser
parser = argparse.ArgumentParser(description='This program takes two input numbers and then calculate the sum.')

Now run 'sum.py -h' to see the help message.

Specify data types

By default, the inputs are taken as strings. If you want to change them to other types, you can use the option 'type'.

parser.add_argument('-n1', '--number1', dest='n1', type=int, required=True)

Here it changed the argument to an integer and you do not need to convert the variable to integer later.

Specify action

You can specify the option 'action' to change what it does to the input arguments. There are six actions that can be triggered when an argument is specified:

To save a list with repeated arguments

parser.add_argument('-n', '--number', dest='n', type=int, action='append')

Set choices

If you want to limit the range of an input argument, you can set the choices option.

parser.add_argument('-n', '--number', dest='n', type=int, choices=range(2,11), action='append')

If the input is out of the choices, the program will exit and return an error message.

Set help message

For each argument, you can specify a guideline, which will appear in the help message, to let users know how to set it.

parser.add_argument('-n1', '--number1', dest='n1', type=int, required=True, help='Please specify the first number.')

Wrapping up

Below is all the codes of the example program. Save it to 'sum.py' and run 'python sum.py -h'.

import argparse
# Create a parser
parser = argparse.ArgumentParser(description='This program takes two input numbers and then calculate the sum. It also remember the input numbers.')
# Add an argument
parser.add_argument('-n1', '--number1', dest='n1', type=int, required=True, help='Please specify the first number.')
parser.add_argument('-n2', '--number2', dest='n2', type=int, required=True, help='Please specify the second number.')
parser.add_argument('-n', '--number', dest='n', type=int, choices=range(2,11), action='append', help='Please add numbers.')
# Parse the arguments
args = parser.parse_args()
# Start programming
print('The two inputs are '+str(args.n1)+' and '+str(args.n2))
sum = args.n1 + args.n2
print('The sum is '+str(sum))
print('The appended argument is')
print(args.n)

This is what the help message looks like.

usage: test.py [-h] -n1 N1 -n2 N2 [-n {2,3,4,5,6,7,8,9,10}]
This program takes two input numbers and then calculate the sum. It also remember the input numbers.

optional arguments:
-h, --help show this help message and exit
-n1 N1, --number1 N1 Please specify the first number.
-n2 N2, --number2 N2 Please specify the second number.
-n {2,3,4,5,6,7,8,9,10}, --number {2,3,4,5,6,7,8,9,10}
Please add numbers.

Run 'python test.py -n1 3 -n2 4 -n 4 -n 2'

The two inputs are 3 and 4
The sum is 7
The appended argument is
[4, 2]

👏 Cool. Now you are ready to write a cool program with arguments by yourself.