Spot the bug: getoptquestion.py

Chris Angelico rosuav at gmail.com
Mon Jul 4 07:36:13 EDT 2016


On Mon, Jul 4, 2016 at 9:24 PM, Oscar <jornws0718 at xs4all.nl> wrote:
> Is this:
>
> a) a bug in getopt.getopt
> b) a bug in my code
> c) a great way to keep me busy for a while
> d) all of the above?
>
>
> #!/usr/bin/python
>
> from __future__ import print_function
> from getopt import getopt, GetoptError
> import sys
>
> try:
>     opts, args = getopt(sys.argv[1:], 'b', ['bug '])
>
> except GetoptError as err:
>     print('Caught:', repr(err))
>
> else:
>     if opts:
>         for opt, arg in opts:
>
>             if opt in ('-b', '--bug'):
>                 print ("Ceci n'est pas un bug!")
>             else:
>                 #print ('Missed option: "{0}"'.format(opt))
>                 print ('Missed option:', opt)
>     else:
>         print('Usage:', sys.argv[0],'-b|--bug')

Well, first thing I'd do is wipe out your try/except. It's not really
achieving much (you effectively catch an exception to print it to the
console and terminate).

But then what I'm seeing is that you have 'bug ' (with a trailing
space) in your list of long options, so getopt returns '--bug ' as a
long option. Is that a bug? I dunno. Why do you have the trailing
space? In any case, it's pretty easy to see if you change one line of
your code to:

print('Missed option: %r' % opt)

ChrisA



More information about the Python-list mailing list