SaltyCrane Blog — Notes on JavaScript and web development

Python optparse example

Optparse seems like a pretty cool module for processing command line options and arguments in Python. It is intended to be an improvement over the old getopt module. Optparse supports short style options like -x, long style options like --xhtml and positional arguments. Optparse also makes it easy to add default options and help text. Below is my optparse example. For more information, see the optparse documentation.

Here is my example file,

#!/usr/bin/env python

from optparse import OptionParser

def main():
    parser = OptionParser(usage="usage: %prog [options] filename",
                          version="%prog 1.0")
    parser.add_option("-x", "--xhtml",
                      help="create a XHTML template instead of HTML")
    parser.add_option("-c", "--cssfile",
                      action="store", # optional because action defaults to "store"
                      help="CSS file to link",)
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("wrong number of arguments")

    print options
    print args

if __name__ == '__main__':

Note: If you do not specify a dest variable, optparse will use the long option name you specify (removing the initial two dashes and substituting underscores for dashes in the middle of the name). If you do not specify a long option, it will use the short option.

displaying the help message

./ -h
Usage: [options] filename

  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -x, --xhtml           create a XHTML template instead of HTML
  -c CSSFILE, --cssfile=CSSFILE
                        CSS file to link

wrong number of arguments

Usage: [options] filename error: wrong number of arguments

using default options

./ myfile.html
{'xhtml_flag': False, 'cssfile': 'style.css'}

specifying command line options

./ -x -c mystyle.css myfile.html
{'xhtml_flag': True, 'cssfile': 'mystyle.css'}

specifying long style command line options

./ --xhtml --cssfile=mystyle.css myfile.html
{'xhtml_flag': True, 'cssfile': 'mystyle.css'}

How to specify a discrete list of choices for an option

from optparse import OptionParser

def main():
    parser = OptionParser(usage='usage: %prog [options] ')
    parser.add_option('-e', '--env',
                      choices=['production', 'staging', 'testing',],
                      help='Environment to run on',)
    (options, args) = parser.parse_args()


#1 TxRx commented on :

Nice article, stumbled across this via Google. Most helpful and I'm liking this optparse module.

#2 Peter Andrews commented on :

Thanks. I was having trouble figuring out the syntax for the choices list.

#3 Juanbuchet commented on :

Thanks, this blog has been very helpful!

#4 TxRx commented on :

Keeps on popping up in those search results and boy am I glad it does :D

Thanks for posting this, the optparse info on Python site is hugely comprehensive but this makes for much more ease of use an understanding on some of my 1st encounters with optparse.

#5 Eoin Ward commented on :

Idiots guide to optparse, exactly what I need :-)

#6 bruce commented on :

an example of a setting like -q for quiet would be good (an item that doesn't accept a value)

#7 TxRx commented on :

For a quieter value you can use boolean action type "store_true" such as:

parser.add_option("-q",action="store_true",dest='quiteMode',help="Run this in 'quiet/non-verbosing' mode",default=False)

which defaults to False if -q is not present.

See: for more

#8 jackw commented on :

As others have pointed out, Thank You for the example on how to use the choices option.

#9 Terence commented on :

Do you think getopt is better? or optparse?