How do I print useful errors with getopt?

Trent Mick trentm at ActiveState.com
Mon Jan 8 13:24:44 EST 2001


On Sun, Jan 07, 2001 at 11:09:17AM +0100, gradha at iname.com wrote:
> Hi.
> 
> Coming from the C world, I got a try at the python getopt module. It works
> nicely, but there are is something I miss: when the user supplies a wrong
> switch combination, I miss getopt reporting the specific error. I can of
> course catch getopt.error, but how can I print to the user what triggered
> the error? Under C it was as easy as not touching opterr: the system would
> then print the conflict in the appropiate localized text.
> 
> I am running Debian Potato with Python 1.5.2, if it's of any use to you.


Here is what I do:


    import sys, getopt

    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'vf:', ['verbose'])
    except getopt.GetoptError, msg:
        sys.stderr.write("error in options: %s\n" % msg)
        sys.exit(1)
    for opt,optarg in optlist:
        if opt in ('-v', '--verbose'):
            verbosity = 1
        elif ...
    ...



Regards,
Trent


-- 
Trent Mick
TrentM at ActiveState.com




More information about the Python-list mailing list