- http://docs.python.org/library/optparse.html
- http://www.python.org/doc/2.5.2/lib/module-optparse.html
A good tutorial: http://blog.doughellmann.com/2007/08/pymotw-optparse.html
This is an simple example of optparse, a command line parser in Python.
You can copy it and modify it free.
# Loading command line parser, this is better.
import optparse
# Loading basic libraries
import sys
# This is command line parser setting
usage = "Usage: #pprog [options] arg"
parser = optparse.OptionParser(usage)
# You can add the options in the following format
parser.add_option('-o', '--output',
dest="output_filename",
default="default.out",
help="Given a output",
)
parser.add_option('-i', '--input',
dest="input_filename",
default="default.in",
help="Given a input",
)
parser.add_option('-v', '--version',
dest="version",
default=1.0,
type="float",
help="Show the version",
)
parser.add_option('-d', '--debug',
dest="debug",
default=False,
action="store_true",
help="Debug mode, all information will be printed in debug.out",
)
parser.add_option('-g', '--graphic',
dest="graphic",
default=False,
action="store_true",
help="Graphic mode, print the result in graphic",
)
options, remainder = parser.parse_args()
# This is main function
# if no option print help()
if len(sys.argv) == 1:
parser.print_help()
# if we have more than one option, print option table
if len(sys.argv) > 1:
print 'ARGV :', sys.argv[1:]
print 'VERSION :', options.version
print 'INPUT :', options.input_filename
print 'OUTPUT :', options.output_filename
print 'DEBUG :', options.debug
print 'GRAPHIC :', options.graphic
# Then you can use the options to setting your variables and parameters
Reminder #1
if you use the function, "defualt", on your options.debug, you won't get the options.debug == None, because options.debug will have a defualt.
So you are impossible to use if statements to get options.debug == None.
If you need the if statements to check options.debug == None, you have to remove the function, options.default.
No comments:
Post a Comment