he recommended command-line parsing module in the Python standard library
1. Basic
import argparse parser = argparse.ArgumentParser() parser.parse_args()
$ python prog.py --help usage: prog.py [-h] optional arguments: -h, --help show this help message and exit
display the usefulness of the argparse module
2. positional argument
eg
import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() print args.echo
result
$ python prog.py usage: prog.py [-h] echo prog.py: error: the following arguments are required: echo $ python prog.py --help usage: prog.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit $ python prog.py foo foo
If we want to change the argument into an integer, we can:
import argparse parser = argparse.ArgumentParser() parser.add_argument("square", help="display a square of a given number", type=int) args = parser.parse_args() print args.square**2
3. optional argument
import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbosity", help="increase output verbosity") args = parser.parse_args() if args.verbosity: print "verbosity turned on"
output
$ python prog.py --verbosity 1 verbosity turned on $ python prog.py $ python prog.py --help usage: prog.py [-h] [--verbosity VERBOSITY] optional arguments: -h, --help show this help message and exit --verbosity VERBOSITY increase output verbosity $ python prog.py --verbosity usage: prog.py [-h] [--verbosity VERBOSITY] prog.py: error: argument --verbosity: expected one argument
4. short option
import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print "verbosity turned on"
output
$ python prog.py -v verbosity turned on $ python prog.py --help usage: prog.py [-h] [-v] optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity