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.
if __name__etc. If they don't do it, that's just their lookout.find_moduleand then inspecting it manually... which still will be flawed as it can pull in code from other places or use a strange encoding like rot13 or other such fun stuff.collections.namedtuplewhich builds a string andexecs it) execute arbitary code. Just like you generally can't check types or check whether it does not use certain functions, you cannot determine what a module does without importing it. You'll have to trust the user to some degree, or execute the code in a fully-blown sandbox (likely not what you want, and likely overkill).