Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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()

7 Comments — feed icon Comments feed for this post


#1 TxRx commented on 2010-04-21:

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


#2 Peter Andrews commented on 2010-05-24:

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


#3 Juanbuchet commented on 2010-07-14:

Thanks, this blog has been very helpful!


#4 TxRx commented on 2010-11-26:

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 2011-02-17:

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


#6 bruce commented on 2011-06-06:

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


#7 TxRx commented on 2011-08-09:

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

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Slicehost