怎么做相当于“import * from module"?使用 Python 的 __import__ 函数? [英] How does one do the equivalent of "import * from module" with Python's __import__ function?
本文介绍了怎么做相当于“import * from module"?使用 Python 的 __import__ 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个带有模块名称的字符串,如何像调用一样导入模块中的所有内容:
Given a string with a module name, how do you import everything in the module as if you had called:
from module import *
即给定字符串 S="module",如何获得以下等价物:
i.e. given string S="module", how does one get the equivalent of the following:
__import__(S, fromlist="*")
这似乎没有按预期执行(因为它没有导入任何东西).
This doesn't seem to perform as expected (as it doesn't import anything).
推荐答案
请重新考虑.唯一比 import *
更糟糕的是 magic import *
.
Please reconsider. The only thing worse than import *
is magic import *
.
如果你真的想:
m = __import__ (S)
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir (m)
for attr in attrlist:
globals()[attr] = getattr (m, attr)
这篇关于怎么做相当于“import * from module"?使用 Python 的 __import__ 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文