动态导入Python模块

时间:2012-03-20 08:47:30

标签: python import

我正在尝试导入名称未知的模块的成员。而不是

import foo

我正在使用:

__import__("foo")

如何为from foo import bar案例实现类似的事情,而不是诉诸“eval”?

更新:似乎fromlist做了伎俩。有没有办法模仿from foo import *fromlist=['*']没有做到这一点。

4 个答案:

答案 0 :(得分:10)

要模拟from foo import *,您可以使用dir获取导入模块的属性:

foo = __import__('foo')
for attr in dir(foo):
    if not attr.startswith('_'):
        globals()[attr] = getattr(foo, attr)

使用from foo import *通常是不受欢迎的,并且我会想象更多地仿效它。

答案 1 :(得分:9)

__import__("foo", fromlist=["bar"])

了解更多信息help(__import__)

答案 2 :(得分:1)

您可以在__import__的帮助下动态导入。 fromlist中有__import__个关键参数来调用from foo import bar

答案 3 :(得分:0)

有时您想要导入许多配置文件中的一个,每个配置文件对于相同的命名变量,dicts等具有不同的值。

你不能这样做:

def mother_function(module, *args, **kwargs):
    from module import variable
    return variable

def call_home_to_mamma():
    import module_42
    return mother_function(module_42)

关于为什么这不起作用的解释高于我的工资等级,并涉及闭包和命名空间。我发现的工作是使用'module_name'作为字符串参数调用mother函数,然后在我真正需要时动态导入特定变量:

def mother_function(module_name, *args, **kwargs):
    exec('from %s import %s' % (module_name, variable))
    variable = eval(variable)
    return variable

def call_home_to_mamma():
    import module_42
    return mother_function(module_42.__name__)

Bingo ....你可以从运行时确定的导入模块中动态导入你想要的任何变量。