我曾经创建过一个exec语句来生成一个在Python2中使用的函数。然而,当我转到Python3时,同样的方法停止了工作
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
... exec(compile("def printt(): print(2)","printt","exec"))
... printt()
...
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in a
NameError: name 'printt' is not defined
>>>
Python 2.7.15+ (default, Nov 27 2018, 23:36:35)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
... exec(compile("def printt(): print(2)","printt","exec"))
... printt()
...
>>> a()
2
>>>
在Python3中,
exec
函数不再能够直接修改本地范围这在^{} 中有记录,请参见注释,其中说明:
还要注意,Python2代码使用的是^{} statement ,尽管您编写它看起来像一个函数,但它是一种完全不同的形式。另请参见this answer以获得更深入的讨论,甚至this answer从Python代码反汇编的角度讨论了这个问题
因此,如果您想访问在
exec()
范围内定义的符号,应该向它传递一个dict(可能是空的,或者预先填充了要在exec()
块中使用的任何变量赋值或函数定义),然后再访问它Python 3中的代码works:
希望这对于您的目的来说足够好
相关问题 更多 >
编程相关推荐