在Python的方法中执行execfile()

pro*_*eek 2 python configuration execfile

我有一个具有PREAMBLE信息的config.py脚本.我可以使用execfile()函数来读取配置文件的内容.

execfile("config.py")
print PREAMBLE
>>> "ABC"
Run Code Online (Sandbox Code Playgroud)

但是,当在方法中调用execfile()时,我有一个错误.

def a():
    execfile("config.py")
    print PREAMBLE

a()
>>> NameError: "global name 'PREAMBLE' is not defined"
Run Code Online (Sandbox Code Playgroud)

怎么了?怎么解决这个问题?

ise*_*dev 5

您需要传递全局字典execfile才能获得相同的结果:

def a():
    execfile("config.py",globals())
    print PREAMBLE

a()
>>> "some string"
Run Code Online (Sandbox Code Playgroud)

如果您不想污染全局命名空间,可以传递本地字典并使用它:

def a():
    config = dict()
    execfile('/tmp/file',config)
    print config['PREAMBLE']

a()
>>> "some string"
Run Code Online (Sandbox Code Playgroud)

作为参考,在上述两种情况下都/tmp/file包含在内PREAMBLE = "some string".