运行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
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)
答案 0 :(得分:0)
是因为exec是python 3中的一个函数,而是python 2中的一个语句? Have a look at this discussion
答案 1 :(得分:0)
Python编译器在遇到print语句时将LOAD GLOBAL,它作为未定义的变量&#39; A&#39;而失败。如果您尝试反汇编代码[import dis],您将看到后端进程调用的执行。
在此给出了一个很好且定义明确的解释 Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3
答案 2 :(得分:0)
如果您真的希望execfunction
在全局范围内执行该功能,则可以执行
def execfunction(code):
exec(code, globals())
然后,这将使对execfunction
的调用在全局范围内执行,而不是仅在函数的本地范围内执行。