Skip to content

Instantly share code, notes, and snippets.

@photonxp
Last active August 29, 2015 13:58
Show Gist options
  • Save photonxp/9973627 to your computer and use it in GitHub Desktop.
Save photonxp/9973627 to your computer and use it in GitHub Desktop.
shows a simple example on how to use optparse module
#!/usr/bin/python
# shows a simple example on how to use optparse module
# works under python2.6.5
# usage 1:
# python optparse_exampe_1.py -o output.txt
# usage 2:
# python optparse_exampe_1.py --help
# usage 3:
# python optparse_exampe_1.py
# the source of this snippet is modified from Doug Hellmann's Python Module of The Week
# http://pymotw.com/2/optparse/index.html
import optparse
# set the parser options
parser = optparse.OptionParser()
parser.add_option('-o', '--output',
# dest keeps the variable name "output_filename"
# to store the value of the option '-o', for later usage.
dest="output_filename",
default="default.out",
help="test help info",
)
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 'VERSION :', options.version
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