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

2024-10-02 02:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

运行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) 

Tags: inforinputismaincodefunctionrunning
3条回答

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在全局范围内执行函数,您可以这样做

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

然后,这将使对execfunction的调用在全局范围内执行,而不是只在函数的本地范围内执行

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

相关问题 更多 >

    热门问题