The getopt Module
The getopt
module used in Example 2-23 contains functions to extract command-line options and
arguments. It can handle both short and long option formats.
The second argument specifies the short options that should be allowed. A colon (:) after an option name means that option must have an additional argument.
Example 2-23. Using the getopt Module
File: getopt-example-1.py import getopt import sys # simulate command-line invocation sys.argv = ["myscript.py", "-l", "-d", "directory", "filename"] # process options opts, args = getopt.getopt(sys.argv[1:], "ld:") long = 0 directory = None for o, v in opts: if o == "-l": long = 1 elif o == "-d": directory = v print "long", "=", long print "directory", "=", directory print "arguments", "=", argslong = 1
directory = directory
arguments = ['filename']
To make getopt
look for long options, as in Example 2-24, pass a list of option descriptors as
the third argument. If an option name ends with an equals sign (=),
that option must have an additional argument.
Example 2-24. Using the getopt Module to Handle Long Options
File: getopt-example-2.py import getopt import sys # simulate command-line invocation sys.argv = ["myscript.py", "--echo", "--printer", "lp01", "message"] opts, args = getopt.getopt(sys.argv[1:], "ep:", ["echo", "printer="]) # process options echo = 0 printer = None for o, v in opts: if o in ("-e", "--echo"): echo = 1 elif o in ("-p", "--printer"): printer = v print "echo", "=", echo print "printer", "=", printer ...
Get Python Standard Library now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.