photon
4/4/2014 - 12:39 PM

optparse_getoptcomparison.py

#!/usr/bin/python

# usage: 
# python optparse_getoptcomparison.py -o output.txt
# works under python2.6.5

# the source of this snippet is from Doug Hellmann's Python Module of The Week
# http://pymotw.com/2/optparse/index.html

import optparse
import sys

# this line shows the result of getopt module?
# the result of sys.argv[1:] is ['-o', 'output.txt']
print '==== getopt result ===='
print 'ARGV      :', sys.argv[1:]

# set the parser options
parser = optparse.OptionParser()
parser.add_option('-o', '--output', 
                  # dest keeps the varible name of the parsed option.
                  dest="output_filename", 
                  default="default.out",
                  )
parser.add_option('-v', '--verbose',
                  dest="verbose",
                  default=False,
                  action="store_true",
                  )
parser.add_option('--version',
                  dest="version",
                  default=1.0,
                  type="float",
                  )

'''
with the parser-option settings added, now optparse can parse the options 
by parse_args()
the parse_args(), by default it uses sys.argv[1:] 
https://docs.python.org/2/library/optparse.html
'''

options, remainder = parser.parse_args()

print '==== optparse result ===='
print 'VERSION   :', options.version
print 'VERBOSE   :', options.verbose
print 'OUTPUT    :', options.output_filename
print 'REMAINING :', remainder