|
(examples taken from LibRef)
from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-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()
# if user typed <yourscript> --file=outfile -q:
options.filename # "outfile"
options.verbose # False
# if user types <yourscript> without options:
options.filename # None
options.verbose # True
optparse is flexible in handling options, thus all of these will be equivalent:
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile
optparse will automatically create the help listing for your options:
usage: <yourscript> [options]
options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout