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()
3
Comments
—
Comments feed for this post
#2 Peter Andrews commented on 2010-05-24:
Thanks. I was having trouble figuring out the syntax for the choices list.
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(4)
-
aws
(8)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(9)
-
conkeror
(2)
-
cygwin
(18)
-
datastructures
(15)
-
datetime
(3)
-
dell
(3)
-
django
(39)
-
emacs
(20)
-
files_directories
(10)
-
install_setup
(7)
-
javascript
(3)
-
keyboard
(6)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
preferences
(8)
-
processes
(3)
-
pyqt
(18)
-
python
(122)
-
ratpoison
(3)
-
regexes
(5)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(13)
-
ssh
(7)
-
subversion
(6)
-
twisted
(6)
-
ubuntu
(60)
-
urxvt
(5)
-
vxworks
(25)
-
webservices
(4)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan
#1 TxRx commented on 2010-04-21:
Nice article, stumbled across this via Google. Most helpful and I'm liking this optparse module.