importargparseparser=argparse.ArgumentParser()parser.add_argument("square",help="display a square of a given number")args=parser.parse_args()printargs.square**2
the value
"store_true". This means that, if the option is specified, assign the value True to args.verbose. Not specifying it implies False.
Short options
If you are familiar with command line usage, you will notice that I haven’t yet touched on the topic of short versions of the options. It’s quite simple:
$ 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
Note that the new ability is also reflected in the help text.
Combining Positional and Optional arguments
Our program keeps growing in complexity:
importargparseparser=argparse.ArgumentParser()parser.add_argument("square",type=int,help="display a square of a given number")parser.add_argument("-v","--verbose",action="store_true",help="increase output verbosity")args=parser.parse_args()answer=args.square**2ifargs.verbose:print"the square of {} equals {}".format(args.square,answer)else:printanswer
And now the output:
$ python prog.py
usage: prog.py [-h][-v] square
prog.py: error: the following arguments are required: square
$ python prog.py 4
16
$ python prog.py 4 --verbose
the square of 4 equals 16
$ python prog.py --verbose 4
the square of 4 equals 16
We’ve brought back a positional argument, hence the complaint.