Command Line Arguments in Python

When I need a new tool, I often code it in Python.  Often, command line options are useful. Sometimes it is possible to have a fixed set of parameters, but this is not very flexible. Fortunately, Python has standard libraries to handle parsing command lines.  There are three libraries providing varying capabilities.  Some of the systems I run on have older versions like Jython 2.1 or Python 2.6.  This limits which libraries I can use without backporting libraries

This document provides examples for four command line processing options.  The examples are for a program that processes files and has an optional argument to report the execution time.

argv

Like many languages Python provides access to the command line in the argv array. This provides maximal flexibility and minimal standardization.

import time
import sys

def usage():
    print ''' usage: %s [-t] files

    options:
        -t, --time  Report the execution time in seconds.''' %((sys.argv[0],))
    exit()

starttime = None

if len(sys.argv) > 1 and sys.argv[1].startswith('-t'):
    starttime = time.time()
    filelist = sys.argv[2:]
else:
    filelist = sys.argv[1:]

if not filelist:
    usage()

processfiles(filelist)
reportelapsed(starttime)

getopt

The getopt module provides a C-style parser which may be familiar. This provides basic option parsing and validation. Is is available on all Python installations I work with.

import time
import sys
import getopt

def usage():
    print ''' usage: %s [-t] files

    options:
        -h, --help  Print this help message
        -t, --time  Report the execution time in seconds.''' %((sys.argv[0],))
    exit()

try:
    opts, args = getopt.getopt(sys.argv[1:], 'ht',
                               ['help', 'time'])
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
        elif opt in ('-t', '--time'):
            starttime = time.time()
except Exception, e:
    print (e)
    usage()

if not args:
    usage()

processlines(args)
reportelapsed(starttime)

optparse

Introduced in Python 2.3 and deprecated in 2.7, the optparse module provides a more functional command line parser. It will set options with defaults and validation. It provides a default help function for which option help can be easily specified.

import time
from optparser import OptionParser

usage = '%prog [options] files...'
parser = OptionParser(usage=usage)
parser.add_option('-t', '--time', dest='time', default=None,
                  action="store_const", const=time.time(),
                  help='Report the execution time in seconds.')
(options, args) = parser.parse_args()
if not args:
    parser.error('No files specified')

processlines(args)
reportelapsed(options.time

argparse

Introduced in 2.7, the argparse module extends the capabilities of the optparse module. It will set options with defaults and validations. This module is a non-transparent upgrade to optparse, and partial upgrade documentation is provided.

import time
import argparse

epilog='''
This program processes a list of files.
'''
parser = argparse.ArgumentParser(epilog=epilog)
parser.add_argument('files', nargs='+', metavar='file',
                    help='files to process.')
parser.add_argument('--time', '-t', default=None,
                    action='store_const', const=time.time(),
                    help='Report the execution time in seconds.')
args = parser.parse_args()

countlines(args.files)
reportelapsed(args.time)