How to compile a string of Python code into a module whose functions can be called?

后端 未结 2 1999
悲哀的现实
悲哀的现实 2021-02-05 21:13

In Python, I have a string of some Python source code containing functions like:

mySrc = \'\'\'
def foo():
    print(\"foo\")

def bar():
    print(\"bar\")
\'\'         


        
2条回答
  •  长发绾君心
    2021-02-05 21:54

    You have to both compile and execute it:

    myMod = compile(mySrc, '', 'exec')
    exec(myMod)
    foo()
    

    You can pass dicts to exec to stop foo from “leaking” out. Combine it with a module object created using types.ModuleType:

    from types import ModuleType
    …
    compiled = compile(mySrc, '', 'exec')
    module = ModuleType("testmodule")
    exec(compiled, module.__dict__)
    

提交回复
热议问题