Skip to content

Instantly share code, notes, and snippets.

@codeswimmer
Forked from yosemitebandit/optparse_testing.py
Created December 20, 2012 21:39
Show Gist options
  • Save codeswimmer/4348795 to your computer and use it in GitHub Desktop.
Save codeswimmer/4348795 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
'''
optparse_testing.py
some recipes from http://www.alexonlinux.com/pythons-optparse-for-human-beings
'''
import optparse
parser = optparse.OptionParser()
# basics
parser.add_option('-n', '--new', help='creates a new object')
parser.add_option('-d', '--delete', help='deletes an object')
parser.add_option('-u', '--modify', help='modifies an object')
# booleans
parser.add_option('-b', help='boolean option', dest='someVar', default=False, action='store_true')
# mandatory arguments
parser.add_option('-m', help='some mandatory option', dest='man', action='store_true')
parser.add_option('-p', help='some other mandatory option', dest='pan', action='store_true')
# store arguments
parser.add_option('-M', help='store multiple args', dest='multi', action='store', metavar='<arg> <arg> <arg>', nargs=3) # calling without nargs defaults to one
(opts, args) = parser.parse_args()
print opts.someVar
mandatories = ['man', 'pan']
for m in mandatories:
if not opts.__dict__[m]: # __dict__ is an attr that holds other attrs
print 'mandatory option missing\n'
parser.print_help()
exit(-1)
for _arg in opts.multi:
print _arg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment