problem with optparse

Robert Kern robert.kern at gmail.com
Tue Dec 2 19:59:53 EST 2008


Neal Becker wrote:
> Robert Kern wrote:
> 
>> Neal Becker wrote:
>>> This example is right out of python library reference.  What's wrong
>>> here?
>>>
>>> import optparse
>>>
>>> def store_value(option, opt_str, value, parser):
>>>     setattr(parser.values, option.dest, value)
>>>
>>> parser = optparse.OptionParser()
>>> parser.add_option("--foo",
>>>                   action="callback", callback=store_value,
>>>                   type="int", nargs=3, dest="foo")
>>>
>>> (opt,args) = parser.parse_args ('--foo a b c'.split())
>>>
>>> [...]
>>> /usr/lib64/python2.5/optparse.pyc in _process_args(self, largs, rargs,
>>> values)
>>>    1423             elif self.allow_interspersed_args:
>>>    1424                 largs.append(arg)
>>> -> 1425                 del rargs[0]
>>>    1426             else:
>>>    1427                 return                  # stop now, leave this
>>>    arg in rargs
>>>
>>> TypeError: 'str' object doesn't support item deletion
>> Dunno. It works for me (i.e. I get the expected "error: option --foo:
>> invalid integer value: 'a'"). Have you tried it outside of IPython?
>>
> yes:
> python test_opt.py 
> Traceback (most recent call last):
>   File "test_opt.py", line 12, in <module>
>     (opt,args) = parser.parse_args ('--foo')

Ah, that's different. parse_args() takes a list, not a string.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list