Closed Thread

Former Employee

Join Date: Nov 2005
Posts: 56
10-12-2007, 02:51 PM
Default Command line processing in Python with Optparse

Parsing your script's command line options from scratch is a pain. There is a function called getopt() which comes from C and is used in many languages such as Perl and Python to help you with this task. But it still requires quite a bit of manual work, and nowadays most scripting languages have gone beyond getopt to make command line options easy to process.

Optparse is a standard part of the Python library. Here is an example of its usage. We will create a function called process_args() that does most of the work.
def process_args():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-a", "--add", action="store_true", dest="add",
                      help="Add a name to my database.")
    parser.add_option("-n", "--name", action="store", dest="name",
                      help="Name to add to my database.")
    return parser.parse_args()
The first add_option() has an action "store_true" with a dest of add. This means that the option is a boolean with no arguments and will store the value of True in a variable called "add". You could also use "store_false" to create a boolean argument that stores a value of False.
The second add_option() has an action of "store", so it does take an argument, which it will put into the variable called "name".
Now that you have created your parsing function, you can call it from your main routine.
(opts, args) = process_args()
if opts.add == True:
    print "You used the --add option.\n"
if is not None:
    print "You used the --name option with the argument of %s\n." %
I didn't need to tell it what to parse, because by default it parses ARGV. I also didn't use the second value returned by process_args. It is a list containg the arguments that you passed to your options.

A nice feature of Optparse is that it automatically creates a --help option based on the help strings you passed to add_option(). Here is what the help output looks like for our script.
$ ./myscript --help
usage: myscript [options]

  -h, --help            show this help message and exit
  -a, --add             Add a name to my database.
  -nNAME, --name=NAME
                        Name to add to my database.
For help on the many other features of Optparse, consult the official documentation at
spry_joseph is offline
Closed Thread


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off

All times are GMT -8. The time now is 10:26 AM. Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 VBulletin Skin by ForumMonkeys.