Command Line Arguments

Python is capable of taking extra parameters, or arguments, from the command line. These arguments can make our scripts more scalable.

There are three ways of handling command-line arguments:

  1. With sys.argv
  2. The getopt module
  3. The argparse module

All three work natively in Python. But, argparse has the most options, so that’s the one we’ll focus on here.

Getting Started

The first step is to initialize the module:

import argparse
 
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()

This sets up a simple parser. There’s one built-in argument, -h or –help which is for help:

> python3 arg-test.py -h
usage: arg-test.py [-h]

options:
  -h, --help  show this help message and exit

If we provide any other arguments, Python will report that the argument is unrecognized, and suggest we use the -h option:

> python3 arg-test.py test
usage: arg-test.py [-h]
arg-test.py: error: unrecognized arguments: test

Positional Arguments

We can add in positional arguments. These are mandatory arguments that must be supplied by a user. They also must be supplied in the right order.

As an example, think of the copy or cp command in Windows or Linux. There are two mandatory arguments that must be supplied; First the source, and then the destination.

import argparse
 
# Initialize parser
parser = argparse.ArgumentParser()

# Create positional (mandatory) arguments
parser.add_argument("arg1")
parser.add_argument("arg2")

# Get the argument list
args = parser.parse_args()

# Print the two arguments
print ("Arg 1 is: " + args.arg1)
print ("Arg 2 is: " + args.arg2)

In the code above, I created two positional arguments called arg1 and arg2, using the add_argument() method. When the script is run, we have to supply these two arguments. They are then stored in the args variable.

When the script is run, it looks like this:

> python3 arg-test.py test message
Arg 1 is: test
Arg 2 is: message

If we don’t include the right amount of arguments, the script will tell us what we should be doing:

> python3 arg-test.py
usage: arg-test.py [-h] arg1 arg2
arg-test.py: error: the following arguments are required: arg1, arg2

Optional Arguments

Optional arguments are exactly how they sound. Arguments that the user can supply if they want to. These are added in the same way as positional arguments, but start with a dash character:

import argparse
 
# Initialize parser
parser = argparse.ArgumentParser()

# Create optional arguments
parser.add_argument("-i", "--input")

# Get the argument list
args = parser.parse_args()

# Print the optional argument
print ("Optional Arg is: " + args.input)

In the example, I’ve included two ways this argument can be formatted. The short way (-i) and the long way (–input). The user can choose whichever they feel comfortable with.

The output looks like this:

> python3 arg-test.py -i filename
Optional Arg is: filename

Options

Options are the same as an optional argument, except the user doesn’t have to provide a value. To put it simply, it turns a feature on or off.

import argparse
 
# Initialize parser
parser = argparse.ArgumentParser()

# Create options
parser.add_argument("-v", "--verbose", action="store_true")

# Get the argument list
args = parser.parse_args()

# Print the option state
if args.verbose:
    print ("Verbose is on")
else:
    print ("Verbose is off")

In the example above, we’re creating an optional argument called verbose. We’re also adding the store_true action. This is a boolean action that sets true if this argument is supplied, or false if it is omitted.

If -v is supplied, the output looks like:

> python3 arg-test.py -v
Verbose is on

And if -v is omitted:

> python3 arg-test.py
Verbose is off

Helping the User

A Help Message

The help message didn’t show much. We can add more information to make life easier. This is done by adding a message as a string:

import argparse
 
# Define a help message
helpmsg = "Thank you for using Network Direction"

# Initialize parser
parser = argparse.ArgumentParser(description = helpmsg)
parser.parse_args()

When a user runs the script with -h our message will be added to the output. The original output will still be present.

Command Help

Help can be added to each command as well. When a user adds -h as an argument, each of the options and arguments has a description listed. The whole script looks like this:

import argparse
 
# Define a help message
helpmsg = "Thank you for using Network Direction"

# Initialize parser
parser = argparse.ArgumentParser(description = helpmsg)

# Create positional (mandatory) arguments
parser.add_argument("arg1", help = "This is the first argument")
parser.add_argument("arg2", help = "This is the second argument")

# Create optional arguments
parser.add_argument("-i", "--input", help = "An optional filename")

# Create options
parser.add_argument("-v", "--verbose", action="store_true", help = "Enable verbose mode")

# Get the argument list
args = parser.parse_args()

# Print the two arguments
print ("Arg 1 is: " + args.arg1)
print ("Arg 2 is: " + args.arg2)
print ("Optional Arg is: " + args.input)
if args.verbose:
    print ("Verbose is on")
else:
    print ("Verbose is off")

The output of this looks like:

> python3 arg-test.py -h
usage: arg-test.py [-h] [-i INPUT] [-v] arg1 arg2

Thank you for using Network Direction

positional arguments:
  arg1                  This is the first argument
  arg2                  This is the second argument

options:
  -h, --help            show this help message and exit
  -i INPUT, --input INPUT
                        An optional filename
  -v, --verbose         Enable verbose mode