I'm trying to get to know optparse
a bit better, but I'm struggling to understand why the following code behaves the way it does. Am I doing something stupid?
import optparse
def store_test(option, opt_str, value, parser, args=None, kwargs=None):
print 'opt_str:', opt_str
print 'value:', value
op = optparse.OptionParser()
op.add_option('-t', '--test', action='callback', callback=store_test, default='test',
dest='test', help='test!')
(opts, args) = op.parse_args(['test.py', '-t', 'foo'])
print
print 'opts:'
print opts
print 'args:'
print args
Output:
opt_str: -t value: None opts: {'test': 'test'} args: ['foo']
Why is 'foo'
not being passed to store_test()
and instead being interpreted as an extra argument? Is there something wrong with op.parse_args(['-t', 'foo'])
?
↓
http://codepad.org/vq3cvE13
Edit:
Here's the example from the docs:
def store_value(option, opt_str, value, parser):
setattr(parser.values, option.dest, value)
[...]
parser.add_option("--foo",
action="callback", callback=store_value,
type="int", nargs=3, dest="foo")