[Python-Dev] RE: Option Parsing Libraries

Mark McEahern marklists@mceahern.com
Mon, 11 Feb 2002 11:16:52 -0800

[Paul Prescod]
> If you have a competitive library, or suggestions for changes to Optik,
> please forward your comments to python-dev mailing list
> (python-dev@python.org).

I love optik.  We use it for all of our option parsing.

I have one feature request related to error handling.  I've attached sample
code below that shows a common thing I end up doing:  raising an error if a
required option is missing.  I guess it's not really an option, then, is it?
<wink>  Anyway, I searched optik's documentation for some way to "inspect"
the options collection itself for the original information used when
creating the option.  In the code below, you'll notice the requiredVar
method takes a description parameter.  It would be nice to be able to do
something like this instead:

	if var is None:
		parser.error("Missing: %s" % options.var.description)

In fact, it would seem that this itself is so common it would be "built-in"
to optik itself.  So that all I have to do is declare an option as required
when I add it with add_option?


// mark

#! /usr/bin/env python
# testError.py

from optik import OptionParser

def requiredVar(parser, options, var, description):
    """Raise a parser error if var is None."""
    if var is None:
        # Here's where it'd be nice to have access to the attributes of the
        # options; at the very least, so I could say which option is missing
        # without having to pass in the description.
        parser.error("Missing: %s" % description)

def parseCommandLine():
    """Parse the command line options and return (options, args)."""

    usage = """usage: %prog [options]
Testing optik's error handling.
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", type="string", dest="filename",
                      metavar="FILE", help="read data from FILE",

    options, args = parser.parse_args()

    requiredVar(parser, options, options.filename, "filename")

def main():
    options, args = parseCommandLine()

if __name__=="__main__":