将模块列为字符串并将其导入 [英] 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
有人知道我能否在python
中做到这一点吗?
Does anybody know if I can to that in python
?
推荐答案
使用importlib.import_module
:
imported_modules = {m: importlib.import_module(m) for m in modules_to_import}
如果要将模块作为全局变量访问,则必须做一些棘手的事情,例如分配给globals()
:
If you want to access the modules as global variables, you'll have to do some hacky stuff, such as assigning to globals()
:
for module in modules_to_import:
globals()[module] = importlib.import_module(module)
这篇关于将模块列为字符串并将其导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文