getopts confusion

Steve Holden sholden at holdenweb.com
Fri Jun 29 08:13:50 EDT 2001


"Rob Brown-Bayliss" <rob at ZOOstation.cc> wrote in ...
> Hi,  I have a problem with getopt on a linux system.
>
> I have two python progs, one works and one does not.  Both import:
> string, sys, getopt
>
>
> This one WORKS:
>
[ unreadable program which works ]
>
>
> This one FAILS with:
>
> Error on option -s: unknown option.
> Run './gearbox.py --help' to see a full list of available command line
> options.
>
> The code is:
>
> global wTree, GearBox, Status, showsum
> try:
> opts, args = getopt.getopt(sys.argv[1:], "hsz", ["help", "summary",
> "zoo"])
> print getopt.getopt(sys.argv[1:], "hsz", ["help", "summary", "zoo"])
> except Error, msg:
> # print help information and exit:
> usage()
> sys.exit(2)
> for o, a in opts:
> if o in ("-h", "--help"):
> usage()
> sys.exit()
> if o in ("-s", "--summary"):
> showsum = 1
> print "ssss"
> if o in ("-z", "--zoo"):
> zoo = 1
>
>
> The one that fails fais for all opts, but if I give args rather than
> options it passes ok (as in I can print the args out)
>
>
> Any one know whats going on?  Any clues are welcome
>
Rob:

Sorry, but the combination of your tabs and my mailreader makes it somewhat
difficult to ensure I got the indentation correct. However:

import getopt, sys
try:
    opts, args = getopt.getopt(sys.argv[1:],
                 "hsz", ["help", "summary", "zoo"])
    print "opts:", opts, "\nargs:", args
except Error, msg:
    print "Got error:", msg

seems to work fine for me:

> cd D:\Steve\Projects\Python
> python optest.py -s -h --zoo


D:\Steve\Projects\Python>python optest.py -s -h --zoo spam eggs spam
opts: [('-s', ''), ('-h', ''), ('--zoo', '')]
args: ['spam', 'eggs', 'spam']

I therefore suspect (**warning**: psychic Python debugging in action here)
an indentation problem in your code. Do I presume correctly that the error
message you report is actually generated by your code? If I try the example
above with an invalid option it actually complains about the Error exception
type (you should really be checking for getopt.GetoptError there):

D:\Steve\Projects\Python>python optest.py -x -h --zoo spam eggs spam
Traceback (most recent call last):
  File "optest.py", line 5, in ?
    except Error, msg:
NameError: There is no variable named 'Error'

I conclude that the getopt code is working correctly, but your application
is somehow failing to test for the options.

Hope this helps.

regards
 Steve
--
http://www.holdenweb.com/






More information about the Python-list mailing list