本文介绍了动态导入Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试导入名称未知的模块的成员。而不是
I am trying to import the members of a module whose name is not known. Instead of
import foo
我正在使用:
__import__("foo")
如何从foo导入栏案例中为实现类似的操作而不是诉诸到eval?
How can I achieve a similar thing for the from foo import bar
case instead of resorting to an "eval"?
更新:似乎 fromlist
做了这个伎俩。有没有办法从foo import * 模拟?
fromlist = ['*']
没有做到这一点。
Update: It seems fromlist
did the trick. Is there a way to emulate from foo import *
? fromlist=['*']
didn't do the trick.
推荐答案
要从foo import * 模拟,你可以使用
dir
获取导入模块的属性:
To emulate from foo import *
you could use dir
to get the attributes of the imported module:
foo = __import__('foo')
for attr in dir(foo):
if not attr.startswith('_'):
globals()[attr] = getattr(foo, attr)
从foo import * 使用通常不赞成并仿效它更是如此,我想。
Using from foo import *
is generally frowned upon, and emulating it even more so, I'd imagine.
这篇关于动态导入Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!