There is a detailed tutorial on how to make use of argparse here. But I wanted to give a quick reference based on a few use cases that I frequently run into.
Terms
Arguments are the strings that you specify with '-x' or '--xxx' in command line.
Values are what you specify following the arguments.
Flags are used to turn something on or off. They are boolean values. Usually a flag is not specified as mandatory.
Mandatory arguments are the arguments without which the program will fail. Specified using required=True to add_argument.
Default values are the values that will be assumed if non-mandatory arguments are not specified. Mandatory arguments cannot have default value. If specified, they will be ignored. Specified using default=xxx to add_argument.
Positional arguments are the ones that are specified with the preceding '-' or '--'. When specifying positional arguments, you can specify the number of values they accept using nargs. '?' means zero or once, '+' means once or more, '*' means zero or more, N means exactly N values.
For the values, you can also specify the accepted type of the individual values using the type=xxx to add_argument. When the type is not specified, the values are stored as strings.
Quick Overview
When the ArgumentParser is parsing the command line arguments that are stored in sys.argv, for each argument specification, there is an action invoked. There are actions like store_true. When invoking the parse_args, the values are parsed and stored in a Namespace.
In the returned namespace, the values can be accessed using dotted notation. For instance, if there is a flag called verbose, in the Namespace returned from parse_args, you can access this flag using args.verbosity.
Example
import argparse
# Assume we have a HTTP server that takes the following arguments.
parser = argparse.ArgumentParser('Http server')
# Optional boolean flag that turns verbosity on.
parser.add_argument('--verbose', default=False, action='store_true', help='Turn verbosity on.')
# Optional argument that specifies the host.
parser.add_argument('--host', default='localhost', help='Host to bind (IP or name). Default is localhost.')
# Mandatory argument that specifis the port
parser.add_argument('--port', type=int, required=True, help='Port to listen in')
# Positional argument that is sent as a response string
parser.add_argument('response', nargs='?', default='hello world!', help='Response string. Default is "hello world!".')
# Now parse the arguments.
args = parser.parse_args()
# Print the parsed values:
print(args)
Sample runs:
# Invoking without any arguments will print a brief help.
$ /tmp/argparsetest.py
usage: Http server [-h] [--verbose] [--host HOST] --port PORT [response]
Http server: error: the following arguments are required: --port
# Invoking with '--help' will print a detailed help.
$ /tmp/argparsetest.py --help
usage: Http server [-h] [--verbose] [--host HOST] --port PORT [response]
positional arguments:
response Response string. Default is "hello world!".
optional arguments:
-h, --help show this help message and exit
--verbose Turn verbosity on.
--host HOST Host to bind (IP or name). Default is localhost.
--port PORT Port to listen in.
# Invoking without a required argument will indicate the missing mandatory arguments.
$ /tmp/argparsetest.py --verbose
usage: Http server [-h] [--verbose] [--host HOST] --port PORT [response]
Http server: error: the following arguments are required: --port
# No errors when the mandatory argument is given
$ /tmp/argparsetest.py --port 8080
Namespace(host='localhost', port=8080, response='hello world!', verbose=False)
# Mixing mandatory and optional arguments.
$ /tmp/argparsetest.py --port 8080 --verbose
Namespace(host='localhost', port=8080, response='hello world!', verbose=True)
# Specifying a positional argument.
$ /tmp/argparsetest.py --port 8080 --verbose 'Sample response'
Namespace(host='localhost', port=8080, response='Sample response', verbose=True)