[Tutor] Getopt difficulty

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 26 Nov 2001 15:03:48 -0800 (PST)


On Mon, 26 Nov 2001, VanL wrote:

> I am trying to use getopt to get options that might have spaces.  For 
> example:
> 
> #!/usr/bin/env python
> 
> import getopt,  sys
> 
> def main():
>     try:
>         opts, args = getopt.getopt(sys.argv[1:], 'sr', ['search', 
> 'replace'])
>         print opts
>         print args
>        
>     except: print "Exception getting opts and args"
>    
> if __name__ == '__main__': main()

According to:

    http://www.python.org/doc/lib/module-getopt.html,

if you want to allow your options to take in an additional argument,
you'll want to append a ':' colon, like this.

###
opts, args = getopt.getopt(sys.argv[1:], 's:r:',
                           ['search', 'replace'])
###

It's not exactly a matter of spacing, but of getopt's surprise: it didn't
expect to read in an option with an argument.  Seen in this light, when we
had done:

> % ./s2.py -s "foo bar" -r foobar

It had thought that "foo bar" was the name of your file, and so it ignored
the rest of the arguments.


Hopet his helps!