我有这段代码:
def test(variable, customCode = ""):
if variable > 1:
print(">1")
if customCode != "":
exec(customCode)
if foo == 1:
print("Success")
numb = 12
code = "if variable > 1: foo = 1"
test(numb, code)
执行时会报错:
所以,然后,我在代码的开头添加了 foo = 0,并得到了这个输出:
现在,很明显,它也应该输出Success,但事实并非如此。
有什么问题?
使用 Python 3。
请您参考如下方法:
正确的方法是在 python 3 中将一个字典传递给 exec 并按键查找,在 python2 中你的代码将按原样工作,因为 exec 是一个语句而不是 python3 中的一个函数:
def test(variable, customCode = ""):
d = {"variable":variable}
if customCode != "":
exec(customCode, d)
if d["foo"] == 1:
print("Success")
numb = 12
code = "if variable > 1: foo = 1"
test(numb, code)
输出:
In [13]: numb = 12
In [14]: code = "if variable > 1: foo = 1"
In [15]: test(numb, code)
Success
Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.
您还需要注意您的 if variable > 1 为 False 的情况,因为您永远不会执行代码,因此永远不会添加 foo。
