Jordan Savant // Software Engineer

Python CLI Arguments

Command line arguments are part of the sys module.

Module sys.argv

main.py

import sys
print(sys.argv)

Running

$ python main.py abc 123
['main.py', 'abc', '123']

Parsing Options

Here is a generalized function for parsing args and options:

def getopts(argv):
    opts = {}  # Empty dictionary to store key-value pairs.
    while argv:  # While there are arguments left to parse...
        if argv[0][0] == '-':  # Found a "-name value" pair.
            opts[argv[0]] = argv[1]  # Add key and value to the dictionary.
        argv = argv[1:]  # Reduce the argument list by copying it starting from index 1.
    return opts

main.py

import sys

args = sys.argv
opts = getopts(args)

if '-i' in opts:  # Example usage.
    print(opts['-i'])

print(opts, args) # args still has all argv values

Running

$ python main.py abc -i 123
123
{'-i': '123'} ['main.py', 'abc', '-i', '123']

Module argparse

Using pip install the argparse module:

pip3 install argparse

Don't name your script argparse.py ;P

Using argparse will automatically create a -h --help option.

Positional Arguments

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("file", help="path to import file")
args = parser.parse_args()

print(args.file)

Setting a required argument will automaticall display usage

$ python main_argparse.py
usage: main_argparse.py [-h] file
main_argparse.py: error: the following arguments are required: file

$ python main_argparse.py -h
usage: main_argparse.py [-h] file

positional arguments:
  file        path to import file

optional arguments:
  -h, --help  show this help message and exit

All options and arguments are strings we want to cast them if needed.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("number", help="number to multiply", type=int)
args = parser.parse_args()

print(args.number ** 2)
$ python main_argparse.py 12
144

Options

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity", action="store_true")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")
$ python main_argparse.py --verbosity
verbosity turned on

Conflicting Options

We can make options mutually exclusive

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
group.add_argument("-q", "--quiet", help="silence output", action="store_true")
parser.add_argument("x", help="exp base", type=int)
parser.add_argument("y", help="exp power", type=int)

args = parser.parse_args()
answer = args.x ** args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("{} to the power of {} equals {}".format(args.x, args.y, answer))
else:
    print("{}^{} == {}".format(args.x, args.y, answer))
$ python main_argparse.py -q -v 2 3
usage: main_argparse.py [-h] [-v | -q] x y
main_argparse.py: error: argument -v/--verbose: not allowed with argument -q/--quiet

$ python main_argparse.py -q 2 3
8

$ python main_argparse.py -v 2 3
2 to the power of 3 equals 8

$ python main_argparse.py 2 3
2^3 == 8