从运行时在运行时加载模块

时间:2011-06-30 17:12:49

标签: python

我想在运行时加载模块。

如果我这样做,那就有效:

a = __import__('datetime',globals(),locals(),[],-1)

for e in a.__dict__:
    if not e.startswith("__"):
        globals()[e] = a.__dict__[e]

但如果我尝试这样做就行不通:

def module_loader(modname,g,l):
    a = __import__(modname,g(),l(),[],-1)

    for e in a.__dict__:
        if not e.startswith("__"):
            g()[e] = a.__dict__[e]


module_loader('datetime',globals,locals)

任何帮助?

2 个答案:

答案 0 :(得分:1)

如果我将其称为

,则上面的代码段对我有用
module_loader('datetime', globals, locals)

答案 1 :(得分:0)

def module_loader(modname,g,l):
    a = __import__(modname,g(),l(),[],-1)

    for e in a.__dict__:
        if not e.startswith("__"):
            g()[e] = a.__dict__[e]

module_loader('datetime', globals, locals)