argparse

2023-04-14 python argparse CLI arguments help generation

I am not very versed in python but recently I worked on old project that used python 2.7. It had hard-coded all inputs within the script. One of my needs was to externalize those parameters, so I could supply different parameters for specific runs.

Looking for nice solution that would allow for help generation and defaults, there is standard built-in module argparse.

import argparse

cli = argparse.ArgumentParser(prog = 'generator', description = 'Builds summary spreadsheet')
cli.add_argument('--reqdir',   help = 'directory with requirements', required=True)
cli.add_argument('--sections', help = 'csv file with sections. Default: %(default)s', default = 'sections.csv')
cli.add_argument('--matrix',   help = 'matrix file. Default: %(default)s', default = 'matrix.xls')
cli.add_argument('--safety',   help = 'safety requirements file. Default: %(default)s', default = 'safety.xls')
cli.add_argument('-v', '--verbose', help = 'verbose output', action='store_true')

args = cli.parse_args()
print("Runtime Args=%s" % args)

The snippet above shows multiple features of the module:

  • parameters to the argparse.ArgumentParser define overall behavior, in this case it specifies name of the program and description used in generated help
  • arguments can use both short and long form as demonstrated with verbose
  • some arguments can be required so the module produces error when it is not specified (reqdir)
  • arguments can have default for the case it is not specified. The %(default)s placeholder can show its value in the help
  • there is multiple possible actions. Default is store to write the specified value into the parsed data, but there is store_true to make it boolean switch like shown with verbose

The behavior is quite nice. When called without parameters, we will get an error

$ python args.py
usage: generator [-h] --reqdir REQDIR [--sections SECTIONS] [--matrix MATRIX]
                 [--safety SAFETY] [-v]
generator: error: argument --reqdir is required

With -h or --help we get nice usage instructions

$ python args.py --help
usage: generator [-h] --reqdir REQDIR [--sections SECTIONS] [--matrix MATRIX]
                 [--safety SAFETY] [-v]

Builds summary spreadsheet

optional arguments:
  -h, --help           show this help message and exit
  --reqdir REQDIR      directory with requirements
  --sections SECTIONS  csv file with sections. Default: sections.csv
  --matrix MATRIX      matrix file. Default: matrix.xls
  --safety SAFETY      safety requirements file. Default: safety.xls
  -v, --verbose        verbose output

When used correctly with specified parameters, it will return and print the namespace with the options

$ python args.py --reqdir . -v
Runtime Args=Namespace(matrix='matrix.xls', reqdir='.', safety='safety.xls', sections='sections.csv', verbose=True)

Usage within the script is simple as we have methods for each parameter

if args.verbose:
    print('Starting')