Python ArgParse Module Notes

Page Contents


  1. The argparse Python docs.


ArgParse Python Module

Really bloody useful for parsing command line options given to scripts with ease!

import argparse

parser = argparse.ArgumentParser(description="Describe your program here")
# Define arguments
args = parser.parse_args()

You can add_argument()'s to the parser. Arguments can be positional or optional. Optional arguments are generally specified as a short command, e.g. -h, and/or as a long command, e.g. --help along with an action to perform if the command is received. Positional arguments are just defined as a name with no preceding hyphenated prefix.


For example, to add version information to the command line you could do:

    "-v", "--version",
    action   = 'version',
    version  = '%(prog)s {version}'.format(version=__version__),
    help     = ("print version information"),

If you want to store the value of an argument in some way you will want to use one of the following actions (there are more possibilities - see the Python docs):

  • store

    To store a conditional you would do something like this:

    parser.add_argument("-j", "--jehtech", action="store")
    args = parser.parse_args() 
    print args.jehtech

    If you then ran your program with the command line argument python --jehtech "Hi JehTech" the variable args.jehtech would hold the string "Hi JehTech"

    To store a positional you would do something like this:

    args = parser.parse_args() 
    print args.jehtech_positional

    If you want your program as python "Hi positional" the variable args.jehtech_positional would hold the string "Hi positional".

  • store_const (and store_true/store_false)

    Use these to store the presense of a flag that has no value associated with it. For example, a verbose flag, probably stands alone, i.e., the flag doesn't have a value associated with it. The const value is what is stored in the parser variable.

        "-T", "--test_mode",
        const    = "This the value to store",
        action   = 'store_const',
    args = parser.parse_args()

    If the option is specified on the command line the property args.test_mode will contain the string "This is the value to store". If it was not specified the property will be None.

    You can specify a default value to be stored if the option is not specified on the command line using the default=... argument to add_argument().

    	"-T", "--test_mode",
        const    = "This the value to store",
        default  = "Default value if --test_mode not specified",
        action   = "store_const",
    args = parser.parse_args()

    The actions store_true and store_false are just shorthand actions for when you would normally set const to either True or False.


        "-T", "--test_mode"
        const    = True
        action   = 'store_const'

    Is equivalent to...

    parser.add_argument( "-T", "--test_mode", action="store_true")
  • append

    This will append values to a list. See Python docs...

Argument Types

By default all arguments are parsed into strings. If you want to have argparse convert the arguments into other types for you, use the type=... parameter of add_argument().

The type= argument takes any callable that accepts a string parameter and returns a type.

So, for example, the int function can be passed to add_argument.

    "-i", "--an-int-param"
    action  = 'store'
    type    = int

If you wanted a positive integer, for example, you could define your own callable...

    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError("Negative integers are not allowed")
    return ivalue

parser = argparse.ArgumentParser(...)
    "-u", "--a-uint-param",
    action = "store",
    type   = positive_int)


If you want to check the values of the parameter match a list of choices, after type conversion you can use the choices=(generator|list) argument.

To restrict a param to a range of integers use choices=range(min,max), or to restrict a string to a list of values use choices=["some", "list", "of", "strings].

Optional Posisitional When Named Argument Provided

If you want to have command --some-arg xxx work when otherwise a positional would be required, e.g., command --any-other-arg xxx position-arg.

Argprase can't do this out-of-the-box. The easiest way appears to be to use nargs="?" for the positional argument and check manually once the arguments have been parsed:

parser.add_argument("positional1", nargs="?")
parser.add_argument("positional-not-needed", required=False)
args = parser.parse_args()

if args.positional_not_needed is None and args.positional1 is None:
    parser.exit(1, "Positional argument required")

Help And Epilog

If you want a chunk of text at the bottom of the help message there are two options.

  1. Pass in the epilog as an argument to the ArgumentParser() constructor using the epilog keyword.
  2. Or, set the epilog property on the ArgumentParser instance.