Python Argument Parsing Example

by James Johnson

Python scripts are tedious and unwieldy without useful and documented command-line options. This is a brief example of how to parse command line arguments in Python using the argparse module.

Python Argument Parsing Example

Jumping right in, below is an example python script that will parse arguments specified on the command line:

#!/usr/bin/env python
# encoding: utf-8

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        __file__,
        description="A simple argparse example"
    )
    # a boolean option
    parser.add_argument("-y", "--yes",
        help="A true/false option",
        action="store_true",
        default=False
    )
    # an integer option
    parser.add_argument("-c", "--count",
        help="An integer option",
        type=int,
        default=1
    )
    # multiple values allowed for this option
    parser.add_argument("-v", "--val",
        help="multiple values for this option",
        nargs="*",
        dest="vals"
    )
    # a positional option
    parser.add_argument("data",
        help="A positional option"
    )

    args = parser.parse_args()
    print(" Yes? {}".format(args.yes))
    print("Count {}".format(args.count))
    print(" Vals {}".format(",".join(args.vals)))
    print(" Data {}".format(args.data))

Running the python script above yields the output:

jelly$> python argparse_example.py -y -c 10 "this is the data" -v val1 val2 val3
 Yes? True
Count 10
 Vals val1,val2,val3
 Data this is the data

argparse Default Help

One of the benefits to using a module such as argparse is that you get a nice, standard-looking help text and error codes when the user runs the script with no arguments and when the user adds the --help argument.

Below is the error text displayed when running the script with no arguments:

jelly$> python argparse_example.py
usage: /tmp/argparse_example.py [-h] [-y] [-c COUNT] [-v [VALS [VALS ...]]] data
/tmp/argparse_example.py: error: too few arguments

Below is the output that results from running the script with a --help argument:

jelly$> python argparse_example.py --help
usage: /tmp/argparse_example.py [-h] [-y] [-c COUNT] [-v [VALS [VALS ...]]] data

A simple argparse example

positional arguments:
  data                  A positional option

optional arguments:
  -h, --help            show this help message and exit
  -y, --yes             A true/false option
  -c COUNT, --count COUNT
                        An integer option
  -v [VALS [VALS ...]], --val [VALS [VALS ...]]
                        multiple values for this option