Main Content

Command line parameter handling in Python via the argparse module

Archive - Originally posted on "The Horse's Mouth" - 2015-12-08 18:55:44 - Graham Ellis

A new example from the Python course just completed - looking at command line parameters through the argparse module from the standard Python library (2.7 and 3.2 onwards), and XML handling through the xml.etree.ElementTree module (2.5 onwards)

Here's code setting up an argument parser:

  parser = argparse.ArgumentParser()
  parser.add_argument('-a', '--all', action='store_true', help='Show all elements')
  parser.add_argument('-r', '--root', action='store_true', help='Show elements at root level')
  parser.add_argument('-v', action='store_true', help='Verbose')
  parser.add_argument('sourcefile', nargs=1, help='File to parse')
  args = parser.parse_args()


And by default, -h and --help are provided:

  munchkin:cambx grahamellis$ ./xmlparserdemo -h 6_context.xml 
  usage: xmlparserdemo [-h] [-a] [-r] [-v] sourcefile
  
  positional arguments:
    sourcefile  File to parse
  
  optional arguments:
    -h, --help  show this help message and exit
    -a, --all   Show all elements
    -r, --root  Show elements at root level
    -v          Verbose
  


Parameters are named within the object returned by the parser, so:

  if args.v:
    print("Running in verbose mode on file %s " % args.sourcefile[0])


And usage lines generated if the program is run with incorrect arguments:

  munchkin:cambx grahamellis$ ./xmlparserdemo -v -all 6_context.xml 
  usage: xmlparserdemo [-h] [-a] [-r] [-v] sourcefile
  xmlparserdemo: error: argument -a/--all: ignored explicit argument 'll'


Complete program using this code [here] ... the program goes on to handle XML data - there's a sample XML file [here].