Play with options in Python

Note: This post is only valid before Python 2.7, because the optparse module is deprecated and will not be developed further; development will continue with the argparse module.

optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: your create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.

Here's an example of using optparse in a simple script:

`from optparse import OptionParser ... parser = OptionParser()
parser.addoption("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE") parser.add
option("-q", "--quiet",
action="store_false", dest="verbose", default=True, help="don't print status messages to stdout")

(options, args) = parser.parse_args()`

argument
A string entered on the command-line, and passed by the shell to execl() or execv(). In Python, arguments are elements of sys.argv[1:](sys.argv[0] is the name of the program being executed). Unix shells also use the term "word".

Option
An argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen ("-") followed by a single letter, e.g. -x or -F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. The GNU project introduced -- followed by a series of hyphen-separated words, e.g. --file or --dry-run. These are the only two option syntaxes provided by optparse.

Written on 08 August 2016