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(
        description="A simple argparse example"
    # a boolean option
    parser.add_argument("-y", "--yes",
        help="A true/false option",
    # an integer option
    parser.add_argument("-c", "--count",
        help="An integer option",
    # multiple values allowed for this option
    parser.add_argument("-v", "--val",
        help="multiple values for this option",
    # a positional option
        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(

Running the python script above yields the output:

jelly$> python -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
usage: /tmp/ [-h] [-y] [-c COUNT] [-v [VALS [VALS ...]]] data
/tmp/ error: too few arguments

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

jelly$> python --help
usage: /tmp/ [-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