在python中的exec语句中导入模块

时间:2017-11-12 10:34:59

标签: python import exec nameerror

我尝试在python中使用 exec(" import __ as tmp")导入模块:

def prepare(self):
    for modName in self._config.modules.keys():
        print(locals())
        exec("import {} as tmp".format(modName))
        print(locals())
        self._moduleInst[modName] = tmp

输出是:

{'modName': 'time', 'self': <pyo.Server.Server object at 0x000001CA17DFB550>}
{'modName': 'time', 'self': <pyo.Server.Server object at 0x000001CA17DFB550>, 'tmp': <module 'time' (built-in)>}

Traceback (most recent call last):
    File "[...]", line 3, in <module>
        startServer(None)
    File "[...]", line 10, in startServer
        server.prepare()
    File "[...]", line 15, in prepare
        self._moduleInst[modName] = tmp
NameError: name 'tmp' is not defined

我得到一个NameError异常,导致python无法找到tmp。如果我打印出所有局部变量,则定义tmp ...

有人知道我做错了什么吗?谢谢!

2 个答案:

答案 0 :(得分:0)

您不能在功能代码中的任何位置声明tmp变量:

def prepare(self):
    for modName in self._config.modules.keys():
        print(locals())
        exec("import {} as tmp".format(modName))
        print(locals())
        self._moduleInst[modName] = vars()['tmp']

exec语句中的 tmp 字符串。所以我想你要做的是:self._moduleInst[modName] = 'tmp',它将字符串tmp保存到你的字典中。

答案 1 :(得分:0)

抱歉,我似乎无法重现这一点。我的代码:

class foo:
    modules = { 'string' : 0 }

    def prepare(self):
        for modName in self.modules.keys():
            print(locals())
            exec("import {} as tmp".format(modName))
            print(locals())
            self.modl = tmp

somevar = foo()
somevar.prepare()
print(somevar.modl.digits)

输出:

{'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>}
{'tmp': <module 'string' from '/usr/lib/python2.7/string.pyc'>, 'modName': 'string', 'self': <__main__.foo instance at 0x7f5c11123128>}
0123456789

Python版本的差异?