Skip to content

Instantly share code, notes, and snippets.

@samuell
Created January 17, 2012 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuell/1627179 to your computer and use it in GitHub Desktop.
Save samuell/1627179 to your computer and use it in GitHub Desktop.
Parse command line options in python
from optparse import OptionParser
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Parse command line options
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
parser = OptionParser()
parser.add_option("-a", "--theaflag", dest="theaflag", type="string",
help="Helpstring, with THEAFLAG", metavar="THEAFLAG")
parser.add_option("-b", "--theaflag", dest="thebflag",
help="Helpstring")
parser.add_option("-c", "--thecflag", dest="thecflag",
help="Helpstring")
(options, args) = parser.parse_args()
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Make sure flags are set
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Require that the settings file param is set
if options.theaflag not in ['alt1', 'alt2', 'alt3']:
sys.exit("No alternative specified for the a flag!")
if not options.thebflag:
sys.exit("B flag not set!")
if not options.thecflag:
sys.exit("C flag not set!")
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
# Use values of command line options
# \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
print("A flag value: %s, B flag value: %s, C flag value: %s" % (options.theaflag,options.thebflag,options.thecflag))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment