gpt4 book ai didi

python - Python 2.7.6 中的执行

转载 作者:行者123 更新时间:2023-11-30 23:16:04 25 4
gpt4 key购买 nike

我正在学习 2.7.6 上的 evalexeccompile 基础知识。

我在 exec 上遇到了障碍,因为运行此命令时出现错误:

exec 'print 5'

错误:

SyntaxError: unqualified exec is not allowed in function 'main' it contains a nested function with free variables (EvalExecCompile.py, line 61)

我发现 exec 在 2.7.6 中是一个表达式,而在 3.x 中是一个函数。问题是,我找不到 2.7.6 中的 exec 的工作示例可供学习。

我知道使用 exec 等的所有危险,但只是想学习如何使用它们以防我需要它们。

有人可以帮忙吗?也许提供一个我可以剖析的工作示例?

谢谢。

我的问题的目标是学习如何在 2.7.6 中正确使用 exec

最佳答案

除非指定上下文,否则不能在具有子函数的函数中使用 exec。来自文档:

If exec is used in a function and the function contains a nested block with free variables, the compiler will raise a SyntaxError unless the exec explicitly specifies the local namespace for the exec. (In other words, "exec obj" would be illegal, but "exec obj in ns (namespace)" would be legal.)

这里是实现exec的代码:

def test2():
"""Test with a subfunction."""
exec 'print "hi from test2"' in globals(), locals()
def subfunction():
return True

test2()

此示例取自:In Python, why doesn't exec work in a function with a subfunction?

关于python - Python 2.7.6 中的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27872138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com