python optparse_example.py
#!/usr/bin/env python
# Author: Greg Caporaso (gregcaporaso@gmail.com)
# optparse_template.py
""" Description
File created on 01 Aug 2009.
Code published via http://blog.caporaso.us.
Feel free to incorporate this code in your work. If
it turns out to be helpful, please considering linking back to my
blog post in a comment, for example:
Code modified from:
http://blog.caporaso.us/2009/08/python-optparse-example-part-1.html
"""
from optparse import OptionParser
def parse_command_line_parameters():
""" Parses command line arguments """
usage = 'usage: %prog [options] output_filepath'
version = 'Version: %prog 0.1'
parser = OptionParser(usage=usage, version=version)
# A binary 'verbose' flag
parser.add_option('-v','--verbose',action='store_true',\
dest='verbose',help='Print information during execution -- '+\
'useful for debugging [default: %default]')
# An example string option
parser.add_option('-s','--string_to_write',action='store',\
type='string',dest='string_to_write',help='a string to write to '+\
'file [default: %default]')
# An example int option
parser.add_option('-i','--int_value',action='store',\
type='int',dest='int_value',help='an integer value to store '+\
'[default: %default]')
# Set default values here if they should be other than None
parser.set_defaults(verbose=False,\
string_to_write="Some example input.")
opts,args = parser.parse_args()
num_args = 1
if len(args) != num_args:
parser.error('A single filepath is required.')
return opts,args
if __name__ == "__main__":
opts,args = parse_command_line_parameters()
verbose = opts.verbose
if verbose:
print 'Writing file: %s.' % args[0]
f = open(args[0],'w')
f.write('%s\n' % opts.string_to_write)
if opts.int_value != None:
f.write('%d\n' % opts.int_value)
f.close()
if verbose:
print 'File written.'
Thanks to the SyntaxHighlighter developers for the JavaScript used to present this code sample.