In the context of a complex application, I need to import user-supplied ‘scripts’. Ideally, a script would have
def init():
blah
def execute():
more blah
def cleanup():
yadda
so I’d just
import imp
fname, path, desc = imp.find_module(userscript)
foo = imp.load_module(userscript, fname, path, desc)
foo.init()
However, as we all know, the user’s script is executed as soon as load_module runs.
Which means, a script can be something like this:
def init():
blah
yadda
yielding to the yadda part being called as soon as I import the script.
What I need is a way to:
- check first whether it has init(), execute() and cleanup()
- if they exist, all is well
- if they don’t exist, complain
- don’t run any other code, or at least not until I know there’s no init()
Normally I’d force the use the same old if __name__ == '__main__' trick, but I have little control on the user-supplied script, so I’m looking for a relatively painless solution. I have seen all sorts of complicated tricks, including parsing the script, but nothing really simple. I’m surprised it does not exist.. or maybe I’m not getting something.
Thanks.
My attempt using the ast module: