How to call a function using optparse? I do not want to use argparse. Here is my code:
from optparse import OptionParser
def print_stuff():
a = "Hello Word"
print a
parser = OptionParser()
parser.add_option("-c",
action = "callback",
callback = print_stuff()
)
(options, args) = parser.parse_args()
But it shows me an error:
optparse.OptionError: option -c: callback not callable: None
What to do?
What if I wanted to do:
from optparse import OptionParser
def print_stuff(a):
a = "Hello Word"
return a
parser = OptionParser()
parser.add_option("-c",
action = "callback",
callback = print_stuff()
)
(options, args) = parser.parse_args()
You want
callback = print_stuff
without the parens. Including the parens invokes the function, and sets callback to the result (the string "Hello Word"), which is not callable. Without the parens, you're referring to the function itself.