Python: Handle Command line arguments with Optparse

By Eric Downing. Filed in Programming, Python, Scripting  |  
TOP del.icio.us digg

Here is my basic script for handling command line arguments in Python(pre version 2.7 when optparse
was deprecated). The optparse library is very useful in not only handling the command line
arguments, but setting up your help menu as well.

You will need to create an OptionParser and the usage argument lets you print the usage statement
for the script. Then you can add options, add groups for options or collect the left over
parameters as a secondary command or list of files. I use this method often as I create scripts
that help automate build processes.

#!/usr/bin/python

import sys, optparse

# This creates an OptionParser object with the usage string.
op = optparse.OptionParser(usage=" %prog [options]")
# This will add an option -m or --mode which takes sets the mode variable as
# True or False
op.add_option("-m","--mode",help="Specify the mode for the command", 
            action="store_true", dest="mode",default=False)
# This parses the options and places the selected options above in the _options
# object and the rest in arguments.
_options,arguments = op.parse_args()

# Checks if no arguments are passed and if so, runs the print_help method of 
# the OptionParser object
if len(sys.argv) == 1:
    op.print_help()

# This was just to show what happened when you did or didn't pass the
# --mode argument.
if  _options.mode:
    print "Mode is on"
else:
    print "Mode is off"

This method is currently deprecated as of version 2.7. I will write a follow-up post that uses
the newer argparse routine to highlight any differences.

Tags: ,

Leave a Reply