回调函数不可调用 [英] Callback function not callable

查看:138
本文介绍了回调函数不可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了python文档,可以从命令行调用函数,因此我使用optparse模块从函数返回大量文本,但是我的代码不起作用!我想我做对了所有事情.

I've read in python documentation that it is possible to call a function from command line, so I've used optparse module to return a huge text from a function but my code doesn't work! I think I've done everything right.

def HelpDoc():
     return """ SOME 
                   HUGE 
                      TEXT """

parser = OptionParser(usage="%prog ConfigFile")
parser.add_option("-g", "--guide", action = "callback", callback=HelpDoc(), help = "Show help documentation")

(options,args) = parser.parse_args()

追踪

    parser.add_option("-g", "--guide", action = "callback", callback=HelpDoc(), help = "Show help documentation")
  File "/Python-2.7.2/lib/python2.7/optparse.py", line 1012, in add_option
    option = self.option_class(*args, **kwargs)
  File "/Python-2.7.2/lib/python2.7/optparse.py", line 577, in __init__
    checker(self)
  File "/Python-2.7.2/lib/python2.7/optparse.py", line 712, in _check_callback
    "callback not callable: %r" % self.callback, self)

推荐答案

HelpDoc()是字符串,而不是回调函数,因此请使用callback=HelpDoc,即:

HelpDoc() is string, not a callback function, so use callback=HelpDoc instead, i.e.:

parser.add_option("-g", "--guide", action = "callback", callback=HelpDoc, help = "Show help documentation")

这里的区别可以通过以下方式看到:

The difference here can be seen by:

>>> type(HelpDoc())
str

>>> type(HelpDoc)
function

因此,这就是为什么抱怨是回调对象不可调用的原因.显然,字符串不能作为函数调用.

So, that is why the complaint is that the callback object is not callable. String clearly cannot be called as a function.

但是,对选项回调有一些进一步的要求,因此,使用上述修复程序,您将仅收到另一个错误(参数过多).有关更多信息和示例,请参见: https://docs.python .org/2/library/optparse.html#optparse-option-callbacks

However, there are certain further requirements for an option callback, so with the fix above you'll just receive another error (too many arguments). For more info and examples, see: https://docs.python.org/2/library/optparse.html#optparse-option-callbacks

所以,这要复杂得多.至少功能签名(可接受的参数)必须正确.

So, it is a bit more complicated than that. At least the function signature (accepted parameters) has to be right.

(正如Shadow9043在其评论中所述,不建议使用optparse,请改用argparse.)

(And as Shadow9043 says in its comment, optparse is deprecated, use argparse instead.)

这篇关于回调函数不可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆