This question already has answers here:
Dynamically importing Python module
                                
                                    (2个答案)
                                
                        
                                4年前关闭。
            
                    
我有一个包含python代码的字符串。有没有一种方法可以使用字符串创建python模块对象而无需其他文件?

content = "import math\n\ndef f(x):\n    return math.log(x)"

my_module = needed_function(content) # <- ???

print my_module.f(2) # prints 0.6931471805599453


请不要建议使用evalexec。我完全需要一个python模块对象。谢谢!

最佳答案

您可以使用imp模块创建一个空模块,然后使用exec将代码加载到该模块中。

content = "import math\n\ndef f(x):\n    return math.log(x)"

import imp
my_module = imp.new_module('my_module')
exec content in my_module.__dict__ # in python 3, use exec() function

print my_module.f(2)


这是我的答案,但不建议在实际应用中使用它。

关于python - 如何通过Python中的内容创建模块对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32525250/

10-12 18:28
查看更多