Each script invoked from the command line in Python has access to any arguments in the sys.argv
list. While the contents of this list are quite predictable, it is rarely necessary to handle them directly. The preferred option is to use the optparse
module and the OptionParser
class from that module.
An instance of OptionParser has methods for adding options (long and short flags) and including parameters with those options (if desired). The action to be taken when an option is encountered is also configurable, including setting a boolean flag, storing a value, or executing a callback function.
Defaults and help text are also covered, as well as error handling. Here is a basic example using the standard features.
The call to parse_args()
returns a two-tuple. The first item in the tuple is an options object containing any parameters or boolean values captured from the command line. The second item is a list containing any additional arguments passed at the end of the command line.
from optparse import OptionParser p = OptionParser() p.add_option('-d', '--debug', action='store_true', dest='debug', help='Turn on debugging') p.add_option('-s', '--speed', action='store', type='int', dest='speed', help='Use a bigger number to go faster') p.add_option('-u', '--username', action='store', type='string', dest='user', help='Provide your username') p.set_defaults(debug=False, speed=0) options, args = p.parse_args() if options.user is None: p.error('Username is required') print 'debug option is: %s' % options.debug print 'speed option is: %s' % options.speed print 'args are: %s' % args
$ python options.py Usage: options.py [options] options.py: error: Username is required
Unless modified in the creation, each instance of OptionParser adds a -h option to print help for the user.
$ python options.py -h Usage: options.py [options] Options: -h, --help show this help message and exit -d, --debug Turn on debugging -s SPEED, --speed=SPEED Use a bigger number to go faster -u USER, --username=USER Provide your username
In the output below, note the value myfile.txt, which was not associated with any flag.
$ python options.py -u me -s 9 myfile.txt debug option is: False speed option is: 9 args are: ['myfile.txt']