Callback function not callable

烈酒焚心 提交于 2019-12-31 04:03:48

问题


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()

Traceback

    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)

回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/24508826/callback-function-not-callable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!