[英]list modules as strings and import them
I have a bunch of modules that I need to import. 我有一堆我需要导入的模块。 For reasons I not permitted to explain the module names must be stored as strings in a list.
由于我不允许解释模块名称的原因必须作为字符串存储在列表中。 In other words I need to do the following:
换句话说,我需要做以下事情:
modules_to_import = ['module1', 'module2', 'module3']
import modules_to_import
Does anybody know if I can to that in python
? 有人知道我是否可以在
python
?
Use importlib.import_module
: 使用
importlib.import_module
:
imported_modules = {m: importlib.import_module(m) for m in modules_to_import}
If you want to access the modules as global variables, you'll have to do some hacky stuff, such as assigning to globals()
: 如果你想作为全局变量访问模块,你将不得不做一些hacky的东西,比如分配给
globals()
:
for module in modules_to_import:
globals()[module] = importlib.import_module(module)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.