运行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)
Python编译器将在遇到print语句时加载GLOBAL,其中它作为未定义的变量“A”失败。如果您尝试反汇编代码[import dis],您将看到后端进程调用的执行
本文给出了一个很好的解释 Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3
是因为exec是python3中的函数,而不是python2中的语句吗? Have a look at this discussion
如果您真的想
execfunction
在全局范围内执行函数,您可以这样做然后,这将使对
execfunction
的调用在全局范围内执行,而不是只在函数的本地范围内执行供参考:https://docs.python.org/3/library/functions.html#exec
相关问题 更多 >
编程相关推荐