The argparse module is very useful for any program where you wish to take command line input. It allows you to easily to define the syntax for input, be it simple or complex, provides clear error messages and guidance to users and makes it trivial for you to consume the arguments passed in. It also allows you to choose meaningful and easy to remember variable names in which to store the data.

In this example, we shall see some command line arguments that could easily be combined with our example of using pandas as a simple database for storing yarn inventory. See also Dynamic Command Line Arguments with Python argparse for a more advanced example
Before we get started, we need to ensure we have the module installed on our machine
pip install argparse
Simple Example
Then we are good to go. In the following program, we import the module, define the set of valid arguments, parse the input from the user, and if valid, proceed to use it. In our case, we selected some of the most useful patterns
- A mandatory parameter, which takes a value, stored in the variable colour.
- 2 optional parameters that also take values, which are stored in their respective variables of ‘quantity’ and ‘weight’.
- 1 optional parameter ‘v’, that if present, we get a value of true stored in our identified variable of ‘verbose’
- A bonus example at the end will show how define a valid set of parameter values
import argparse
# Define out expected input and what we want the variables to be called
parser = argparse.ArgumentParser( prog='exampleParser',
description='This program demonstrates how to use argparse',
epilog='Use -h for help.')
parser.add_argument('colour') # positional argument
parser.add_argument('-q', '--quantity') # optional value for quantity
parser.add_argument('-w', '--weight') # optional value for weight
parser.add_argument('-v', '--verbose', action='store_true')
# Parse the input from the user
args = parser.parse_args()
# If ok, use the input
if (args.verbose):
print("Lots of yarn available")
print("\tColour: " + args.colour + "; Weight: " + str(args.weight) + "; Quantity: " + str(args.quantity))
else:
print(args.colour, args.weight, args.quantity)
Running this program with all the correct inputs, we get
> python exampleParser.py blue -q 2 -w lace -v
Lots of yarn available
Colour: blue; Weight: lace; Quantity: 2
> python exampleParser.py blue -q 2 -w lace
blue lace 2
As we didn’t make the the weight or colour parameters mandatory, so we can run without them
> python exampleParser.py blue
blue None None
But if we don’t provide the colour, which is mandatory, we can an error message
> python exampleParser.py -q 3
usage: exampleParser [-h] [-q QUANTITY] [-w WEIGHT] [-v] colour
exampleParser: error: the following arguments are required: colour
And when in doubt, we can use the -h option to get the full command line usage
> python exampleParser.py -h
usage: exampleParser [-h] [-q QUANTITY] [-w WEIGHT] [-v] colour
This program demonstrates how to use argparse
positional arguments:
colour
options:
-h, --help show this help message and exit
-q QUANTITY, --quantity QUANTITY
-w WEIGHT, --weight WEIGHT
-v, --verbose
Use -h for help.
List of valid values for a Parameter
As promised, the following example shows how we can replace the open field we had above for colour and restrict the values. The rest of the code is the same a before.
valid_colours = ["pink","blue","red","yellow","white","black", "green"]
parser.add_argument('colour',choices=valid_colours) # positional argument
Then if we run with a valid colour we are fine, but with an invalid one, we get an error message.
> python exampleParser.py blue
blue None None
> python exampleParser.py bluegreen
usage: exampleParser [-h] [-q QUANTITY] [-w WEIGHT] [-v] {pink,blue,red,yellow,white,black,green}
exampleParser: error: argument colour: invalid choice: 'bluegreen' (choose from 'pink', 'blue', 'red', 'yellow', 'white', 'black', 'green')