简体   繁体   English

为什么在python3中的函数内部运行exec失败?

[英]Why running exec inside function fail in python3?

Results running the code for python3: 运行python3代码的结果:

------- input option 1 - exec code is executed --------
0 - for running inside function, 1 - for running in main programa: 1
option = 1
10

------- input option 0 - exec code not executed inside function ----
0 - for running inside function, 1 - for running in main programa: 0
option = 0
code inside execfunction => A = 10
Traceback (most recent call last):
  File "myexec.py", line 19, in <module>
    print(A)    
NameError: name 'A' is not defined
---------------------Code --------------------------

myexec.py myexec.py

def execfunction(icode):
    print('code inside execfunction => %s' %(icode))
    exec(icode)

option = int(input("0 - for running inside function, 1 - for running in main programa: "))

print('option = %d' %(option))

code = 'A = 10'

if (option == 1):
    exec(code)
else:
    execfunction(code)  

print(A) 

Is it because exec is a function in python 3 but a statement in python 2? 是因为exec是python 3中的函数,而是python 2中的语句吗? Have a look at this discussion 看看这个讨论

Python compiler will LOAD GLOBAL on encountering the print statement, where it fails as undefined variable 'A'. Python编译器在遇到print语句时将加载GLOBAL,在该处,它作为未定义变量'A'失败。 If you try to disassemble your code [import dis], you will get to see the execution of the backend process call. 如果您尝试反汇编代码[import dis],则将看到后端流程调用的执行情况。

A nice and well defined explanation is given in this Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3 本文在python 3中的函数中创建动态命名的变量/在python 3中了解exec / eval / locals中给出了一个很好且定义明确的解释

If you really want execfunction to execute the function in the global scope, you can do 如果您确实希望execfunction在全局范围内执行该函数,则可以执行

def execfunction(code):
    exec(code, globals())

Then, this will make the calls to execfunction execute in the global scope, instead of only in the local scope of the function. 然后,这将使对execfunction调用在全局范围内执行,而不是仅在函数的局部范围内执行。

For reference: https://docs.python.org/3/library/functions.html#exec 供参考: https : //docs.python.org/3/library/functions.html#exec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM