How to handle wrong input in getopt package in Python?

skip at pobox.com skip at pobox.com
Fri Aug 25 11:00:56 EDT 2006


    Daniel> getopt.GetoptError: option --imageDir requires argument

Which is precisely what the getopt module should do.

    Daniel> Is there any method in getopt or Python that I could easily
    Daniel> check the validity of each command line input parameter?

Getopt already did the validity check for you.  Just catch its exception,
display a meaningful usage message, then exit, e.g.:

    try:
        o, a = getopt.getopt(sys.argv[1:], 'h', ['imageDir='])
    except getopt.GetoptError, msg:
        usage(msg)
        raise SystemExit                   # or something similar

My usual definition of usage() looks something like this:

    def usage(msg=""):
        if msg:
            print >>sys.stderr, msg
            print >>sys.stderr
        print >> sys.stderr, __doc__.strip()

This will display the module-level doc string for the user.  I find that a
convenient place to document the usage of scripts.  For more complex
programs where command line arg processing is in a separate module you may
have to do something like:

    def usage(msg=""):
        if msg:
            print >>sys.stderr, msg
            print >>sys.stderr
        import __main__
        print >> sys.stderr, __main__.__doc__.strip()

Skip



More information about the Python-list mailing list