Python eval不在函数内部工作

时间:2016-12-19 16:15:48

标签: python function global-variables exec eval

为什么Python eval在函数内不起作用?相同的eval(compile(cmd))代码在全局环境中有效,但在foo函数内不起作用。

简单示例:

fn = '/tmp/tmp'
mode = 'single'

def foo(cmd, fn, mode):
    eval(compile(cmd, fn, mode)) # <<< this does not work
    print 'foo: cmd=', cmd
    print 'foo: x=', x

cmd = "x = 1"
eval(compile(cmd, fn, mode)) # <<< this works
print 'global scope: cmd=', cmd
print 'global scope: x=', x

del(x)
foo('x = 9', fn, mode)

这是输出和错误消息:

global scope: cmd= x = 1
global scope: x= 1
foo: cmd= x = 9
foo: x=
Traceback (most recent call last):
  File "ctest.py", line 20, in <module>
    foo('x = 9', fn, mode)
  File "ctest.py", line 12, in foo
    print 'foo: x=', x
NameError: global name 'x' is not defined

1 个答案:

答案 0 :(得分:4)

在您的函数中,执行确实有效,但x最终在locals()中,然后print语句尝试在x中找到globals()并且所以提出了NameError

fn = '/tmp/tmp'
mode = 'single'

def foo(cmd, fn, mode):
    eval(compile(cmd, fn, mode))
    print 'locals:', locals()
    print 'foo: cmd=', cmd
    print 'foo: x=', locals()['x']

cmd = "x = 1"
eval(compile(cmd, fn, mode))
print 'global scope: cmd=', cmd
print 'global scope: x=', x

del(x)
foo('x = 9', fn, mode)

输出:

global scope: cmd= x = 1
global scope: x= 1
locals: {'x': 9, 'cmd': 'x = 9', 'mode': 'single', 'fn': '/tmp/tmp'}
foo: cmd= x = 9
foo: x= 9