Especially when writing small Python utility programs, it can be tempting to use sys.argv to retrieve a small list of positional parameters from the command line. But small utilities turn into successful tools over time, and manually parsing optional parameters and switches will quickly overwhelm your code logic.
In this article I will show how the standard argparse library can be used to easily handle argument parsing.
Example Summary
This small program we will use in this example is argParseTest.py. It takes two mandatory integer parameters from the command line, and performs a mathematical operation on them. By default it adds.
For example, the simplest invocation is the addition of 3 and 4 to get 7:
$ ./argParseTest.py 3 4 3 add 4 = 7
If you supply an optional parameter, you can multiply instead to get 12:
$ ./argParseTest.py 3 4 --op=mul 3 mul 4 = 12
And an optional flag gets the operation string in upper case:
$ ./argParseTest.py 3 4 --to-upper 3 ADD 4 = 7
Example Code
The parsing of the command line arguments describe above is made possible with the standard library named argparse. You can download the full code at argParseTest.py from github, or refer to the snippet below:
import argparse . . . # define arguments ap = argparse.ArgumentParser(description="Example using ArgParse library") # mandatory args ap.add_argument('a',type=int,help="first integer") ap.add_argument('b',type=int,help="second integer") # optional args start with hyphen ap.add_argument('-o','--op',default="add",choices=['add','mul'],help="add or multiply") ap.add_argument('-u','--to-upper',action="store_true",help="show uppercase") # parse args args = ap.parse_args() # now use arguments in any way you choose show_math_result(args.a,args.b,args.op,args.to_upper)
As you can see, the library takes care of parameter types, strict choices, optional flags, defaults, and much more. This allows you to keep your code terse, and is more maintainable than raw sys.argv parsing.
Help Summary
And if your users need to see a full usage message, they can use “–help” as shown below.
$ ./argParseTest.py --help usage: argParseTest.py [-h] [-o OP] a b Example using ArgParse library positional arguments: a first integer b second integer optional arguments: -h, --help show this help message and exit -o {add,mul}, --op {add,mul} add or multiply -u, --to-upper show uppercase
REFERENCES
stackoverflow, argparse and optparse
stackoverflow, using epilog with argparse to show example usage
NOTES
use nargs for optional positional args or var args
ap.add_argument('c', type=int, nargs='?', help="third integer")