Parsing command line options in Python

import sys, getopt, os.path me = os.path.basename(sys.argv[0]) debug = False really = True verbose = False my_options = ( ("d", "debug", "debug = True", "Enable debug mode."), ("n", "notreally", "really = False", "No action, display only."), ("v", "verbose", "verbose = True", "Increase verbosity.") ) short_opts = reduce(lambda a, b: a + b[0], my_options, "") long_opts = map(lambda x: x[1], my_options) def usage (): args = "[-%s] <dir1> <dir2> [...]" % short_opts print >> sys.stderr, "Usage: ", me, args, "\nOptions:" for opt in my_options: print >> sys.stderr, "-" + opt[0], opt[3] sys.exit(1) try: opts, args = getopt.getopt(sys.argv[1:], short_opts, long_opts) except getopt.GetoptError: usage() for o, p in opts: for shrt, lng, action in my_options: if o[1:] in shrt or o[2:] == lng: exec action break else: usage() if len(args) < 2: usage()
Code snippet for parsing command line options (using the getopt module) in a sophisticated way.

In this example, the program accepts three options (both as one-letter options and as long options) and requires at least two arguments.


#python #code #cesarnog #commandLine

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.