User Tools

Site Tools


python:optparse

Deal with command line arguments using OptionParser

07.02.2011

Check the code below (self explanatory):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import optparse
import os
 
PROGRAM = "example_script"
VERSION = "0.1 alpha"
DESCRIPTION = "Here is some description of what this script can do (or not)"
 
 
def main():
    p = optparse.OptionParser(description = DESCRIPTION,
                              prog = PROGRAM, 
                              version = VERSION,
                              usage = "%prog [OPTIONS] argument")
    p.add_option('--file', '-f', action="store", type="string", dest="filename")
    p.add_option("-n", 
                type="int", dest="n_integer",
                help = "For integer arguments")
    p.add_option("-s", 
                type = "float", dest = "n_float",
                help = "For float arguments")
    p.add_option("-v", "--verbose",
                action = "store_true", dest = "verbose", default=False,
                help = "Set this if you want verbose results")
    (options, arguments) = p.parse_args()
 
    if len(arguments) == 1:
        print "Argument was %s" % (arguments[0],)
 
        print "Integer option -> %d" % (options.n_integer, )
        print "Set verbose? %s" % (options.verbose, )
 
    else:
        p.print_help()
 
 
 
if __name__ == '__main__':
    main()

References:

Full Documentation

python/optparse.txt · Last modified: 2013/03/16 17:41 (external edit)