Python argparse for Command Line

Intro of argparse

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv(see the following part for the details of this).

You can’t keep using Jupyter notebook all the time. The scripts files and a whole projects needs to be created for our task. The argparse is the communication tools which let developers to make changes to the script from the terminal and don’t need to go into the code and change the parameters.

example

1
2
3
4
5
6
7
8
9
10
11
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

This is a program that takes a list of integers and produce either the sum or the max.

Assume the name of file is prog.py, and execute the file:

1
2
3
4
5
python prog.py 1 2 3 4
# output: 4

python prog.py 1 2 3 4 --sum
# output: 10

See the details from docs of argparse.

Else

sys.argv

During using the argparse module, sys.argv is important since you may need it in the main()function.

Code is sometimes like this:

1
2
3
4
5
6
7
8
9
10
import argparse
import sys

def main(argv):
parser = argparse.ArgumentParser()
# parser.add_argument()
# Do some argument parsing

if __name__ == '__main__':
main(sys.argv)

sys.argv is the list of commandline arguments passed to the Python program. It represents all the items that come along via the command line input.

For the content of argv, the first argument is always the script name, and it is also counted in the number of arguments. So even if you don’t pass any argument into your script, the sys.argv variable always contains at least one element and it’s the script name.

Example

Execute this python script, assume it is named test.py.

1
2
3
4
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)
1
python test.py

The output should be:

1
2
3
This is the name of the script:  sysargv.py
Number of arguments in: 1
The arguments are: ['test.py']

Reference

  1. python docs: argparse
  2. How to use sys.argv in Python ](https://www.pythonforbeginners.com/system/python-sys-argv)
  3. https://appdividend.com/2019/01/22/python-sys-argv-tutorial-command-line-arguments-example/