0

在我的main()函数中,我打开一个配置文件:

cfg = {}
execfile("config.conf", cfg)

config.conf 看起来像这样:

x = 10

后来,我使用cfg[x],这给了我NameError: global name 'x' is not defined. 我从这里举了一个例子,我如何使用它,对我来说看起来是正确的。

为什么我会收到这个错误?

4

1 回答 1

1

在链接的问题中,使用与标识符名称匹配的字符串访问值:

print config["value1"]

同样,您应该使用字符串。

cfg["x"]

例子:

cfg = {}
exec("x=23", cfg)
print cfg["x"]

结果:

23
于 2013-11-26T21:08:03.337 回答