Optparse 回调不消耗参数
我试图更好地了解 optparse,但我很难理解为什么以下代码的行为方式如此。我是不是在做蠢事?
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
输出:
opt_str: -t value: None opts: {'test': 'test'} args: ['foo']
为什么'foo'
没有被传递给store_test()
而是被解释为额外的参数? op.parse_args(['-t', 'foo'])
有问题吗?
↓
http://codepad.org/vq3cvE13
编辑:
这是文档中的示例:
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")
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您缺少“type”
或“nargs”选项属性:此选项将导致它消耗下一个参数。
参考:
http://docs.python.org/library/optparse.html#optparse -选项回调
这似乎是来自
optparse.py
的相关代码:You're missing a "type"
or "nargs"option attribute:This option will cause it to consume the next argument.
Reference:
http://docs.python.org/library/optparse.html#optparse-option-callbacks
This seems to be the relevant code from
optparse.py
: