Optparse 回调不消耗参数

发布于 2024-11-18 16:19:17 字数 1137 浏览 5 评论 0原文

我试图更好地了解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

任谁 2024-11-25 16:19:17

您缺少“type”或“nargs”选项属性:

op.add_option('-t', '--test', action='callback', callback=store_test, default='test',
    dest='test', help='test!', type='str')

此选项将导致它消耗下一个参数。

参考:
http://docs.python.org/library/optparse.html#optparse -选项回调

类型
有其通常的含义:与“store”或“append”操作一样,它指示 optparse
使用一个参数并将其转换为类型。而不是存储转换后的
不过,optparse 将其传递给您的回调函数。

纳尔格斯
也有其通常的含义:如果提供并且> 1、optparse会消耗nargs
参数,每个参数都必须可转换为类型。然后它传递一个转换后的元组
您的回调的值。

这似乎是来自 optparse.py 的相关代码:

def takes_value(self):
    return self.type is not None

def _process_short_opts(self, rargs, values):
    [...]
        if option.takes_value():
            # Any characters left in arg?  Pretend they're the
            # next arg, and stop consuming characters of arg.
            if i < len(arg):
                rargs.insert(0, arg[i:])
                stop = True

            nargs = option.nargs
            if len(rargs) < nargs:
                if nargs == 1:
                    self.error(_("%s option requires an argument") % opt)
                else:
                    self.error(_("%s option requires %d arguments")
                               % (opt, nargs))
            elif nargs == 1:
                value = rargs.pop(0)
            else:
                value = tuple(rargs[0:nargs])
                del rargs[0:nargs]

        else:                       # option doesn't take a value
            value = None

        option.process(opt, value, values, self)

You're missing a "type" or "nargs" option attribute:

op.add_option('-t', '--test', action='callback', callback=store_test, default='test',
    dest='test', help='test!', type='str')

This option will cause it to consume the next argument.

Reference:
http://docs.python.org/library/optparse.html#optparse-option-callbacks

type
has its usual meaning: as with the "store" or "append" actions, it instructs optparse
to consume one argument and convert it to type. Rather than storing the converted
value(s) anywhere, though, optparse passes it to your callback function.

nargs
also has its usual meaning: if it is supplied and > 1, optparse will consume nargs
arguments, each of which must be convertible to type. It then passes a tuple of converted
values to your callback.

This seems to be the relevant code from optparse.py:

def takes_value(self):
    return self.type is not None

def _process_short_opts(self, rargs, values):
    [...]
        if option.takes_value():
            # Any characters left in arg?  Pretend they're the
            # next arg, and stop consuming characters of arg.
            if i < len(arg):
                rargs.insert(0, arg[i:])
                stop = True

            nargs = option.nargs
            if len(rargs) < nargs:
                if nargs == 1:
                    self.error(_("%s option requires an argument") % opt)
                else:
                    self.error(_("%s option requires %d arguments")
                               % (opt, nargs))
            elif nargs == 1:
                value = rargs.pop(0)
            else:
                value = tuple(rargs[0:nargs])
                del rargs[0:nargs]

        else:                       # option doesn't take a value
            value = None

        option.process(opt, value, values, self)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文