python 3 exec()globals()和locals()

时间:2019-08-07 04:13:14

标签: exec python-3.6

我在不同的环境中有四个对同一脚本的调用,只有前三个成功。系统提供失败原因的原因为“未找到Fibnacci()。”,但在之前的三个调用中也未找到。因此,前三个呼叫成功的原因很令人困惑?

def isFun():
    #testFibtest2.py
    with open('testFib.py') as f:

        exec('print(dir())',globals())
        exec('print(dir())',{})
        exec('print(dir())')
        exec('print(dir())',{},{})

        code = compile(f.read(), 'testFib.py', 'exec')

        exec('print(dir())',globals())
        exec('print(dir())',{})
        exec('print(dir())')
        exec('print(dir())',{},{})

        exec(code,globals())
        exec(code,{})
        exec(code)
        exec(code,{},{})
isFun()

def Fibonacci(n):
    #testFib.py
    if n<0: 
        print("Incorrect input") 
    # First Fibonacci number is 0 
    elif n==1: 
        return 0
    # Second Fibonacci number is 1 
    elif n==2: 
        return 1
    else: 
        return Fibonacci(n-1)+Fibonacci(n-2) 

# Driver Program 

print(Fibonacci(9)) 

并输出:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'isFun']
['__builtins__']
['f']
[]
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'isFun']
['__builtins__']
['code', 'f']
[]
21
21
21
Traceback (most recent call last):
  File "testFibtest2.py", line 20, in <module>
    isFun()
  File "testFibtest2.py", line 19, in isFun
    exec(code,{},{})
  File "testFib.py", line 17, in <module>
    print(Fibonacci(9))
  File "testFib.py", line 13, in Fibonacci
    return Fibonacci(n-1)+Fibonacci(n-2)
NameError: name 'Fibonacci' is not defined

1 个答案:

答案 0 :(得分:0)

根据Python 3文档,在第4次调用中,由于全局变量和局部变量都传递给exec(),因此代码的执行就像在类中一样。那么Fibonacci是该类中的方法,因此不能称为Fibonacci()。事实上,由于无法创建“类”的实例,因此无法正确调用它。