Callback function not callable

2019-03-01 10:37发布

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条回答
Luminary・发光体
2楼-- · 2019-03-01 11:07

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

查看更多
登录 后发表回答