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 preceeding hypenated prefix.

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

parser.add_argument( "-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):