Last active
August 29, 2015 13:58
-
-
Save photonxp/9973896 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment