当我在不传递globals或locals参数的情况下调用execfile时,它会在当前命名空间中创建对象,但是如果我调用execfile并为globals(和/或locals)指定dict,它会在__builtin__命名空间中创建对象。
举个例子:# exec.py
def myfunc():
print 'myfunc created in %s namespace' % __name__
exec.py是main.py中的execfile,如下所示。# main.py
print 'execfile in global namespace:'
execfile('exec.py')
myfunc()
print 'execfile in custom namespace:'
d = {}
execfile('exec.py', d)
d['myfunc']()
当我从命令行运行main.py时,得到以下输出。execfile in global namespace:
myfunc created in __main__ namespace
execfile in custom namespace:
myfunc created in __builtin__ namespace
在第二种情况下,为什么要在__builtin__命名空间中运行它?
此外,如果我试图从__builtins__运行myfunc,就会得到一个AttributeError。(这是我希望发生的事情,但是为什么__name__设置为__builtin__?)>>> __builtins__.myfunc()
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: 'module' object has no attribute 'myfunc'
有人能解释这种行为吗?
谢谢