Jordan Savant # Software Engineer

Python CLI Arguments

Command line arguments are part of the sys module.

Module sys.argv

import sys


$ python abc 123
['', '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

import sys

args = sys.argv
opts = getopts(args)

if '-i' in opts:  # Example usage.

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


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

Module argparse

Using pip install the argparse module:

pip3 install argparse

Don't name your script ;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()


Setting a required argument will automaticall display usage

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

$ python -h
usage: [-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 12


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

$ python -q 2 3

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

$ python 2 3
2^3 == 8