相关疑难解决方法(0)

Python 2和Python 3中exec函数的行为

下面的代码给出了不同的输出Python2和在Python3:

from sys import version

print(version)

def execute(a, st):
    b = 42
    exec("b = {}\nprint('b:', b)".format(st))
    print(b)
a = 1.
execute(a, "1.E6*a")
Run Code Online (Sandbox Code Playgroud)

Python2 打印:

2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
('b:', 1000000.0)
1000000.0
Run Code Online (Sandbox Code Playgroud)

Python3 打印:

3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
b: 1000000.0
42
Run Code Online (Sandbox Code Playgroud)

为什么Python2将函数b内部的变量绑定到execute函数字符串中的exec值,Python3而不执行此操作?我怎样才能实现Python2in 的行为Python3?我已经尝试将全局和本地的字典传递给exec函数Python3,但到目前为止还没有任何工作.

---编辑---

在阅读了Martijns的回答后,我进一步分析了这一点 …

python exec python-2.7 python-3.x

38
推荐指数
2
解决办法
3万
查看次数

标签 统计

exec ×1

python ×1

python-2.7 ×1

python-3.x ×1