-
-
Save codeswimmer/4348795 to your computer and use it in GitHub Desktop.
This file contains hidden or 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/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