import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec my_code in mymodule.__dict__
In Python 3, exec is a function, so this should work:
import sys,imp
my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec(my_code, mymodule.__dict__)
Now access the module attributes (and functions, classes etc) as:
print(mymodule.a)
>>> 5
To ignore any next attempt to import, add the module to sys:
sys.modules[‘mymodule’] = mymodule
本文介绍如何使用Python的imp模块和exec函数动态创建并执行模块代码,包括在Python3中的正确用法,以及如何将创建的模块加入到sys.modules中以避免重复导入。

509

被折叠的 条评论
为什么被折叠?



