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, optparse_ex.py:

#!/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",
                      action="store_true",
                      dest="xhtml_flag",
                      default=False,
                      help="create a XHTML template instead of HTML")
    parser.add_option("-c", "--cssfile",
                      action="store", # optional because action defaults to "store"
                      dest="cssfile",
                      default="style.css",
                      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__':
    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

./optparse_ex.py -h
Usage: optparse_ex.py [options] filename

Options:
  --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

./optparse_ex.py
Usage: optparse_ex.py [options] filename

optparse_ex.py: error: wrong number of arguments

using default options

./optparse_ex.py myfile.html
{'xhtml_flag': False, 'cssfile': 'style.css'}
['myfile.html']

specifying command line options

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

specifying long style command line options

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


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',
                      type='choice',
                      action='store',
                      dest='environment',
                      choices=['production', 'staging', 'testing',],
                      default='production',
                      help='Environment to run on',)
    (options, args) = parser.parse_args()

Comments


#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: http://docs.python.org/library/optparse.html#defining-options 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?