感觉以下Python代码应该能够在所有情况下运行(如果打印和范围显然保持不变)。
for i in range(5):
print(i)
print([(i,j) for j in range(i)])
在exec下运行时,我发现此代码返回错误的一些情况。这是Python方面的错误,还是我错过了什么?
import traceback
code_str = r"""
print('\nExec output:')
for i in range(3):
print(i)
print([(i,j) for j in range(i)])
"""
exec_params = [[None, None],
[None, globals()],
[locals(), None],
[{}, None],
[{}, {}],
[None, {}]]
for param0, param1 in exec_params:
try:
#scrubb all variables that could leak from exec
try: del i
except: pass
exec(code_str, param0, param1)
except Exception as e:
print(traceback.format_exc())
Python 2.7.12 | Python 3.4.4
|
-------------------------------------------------------------------------------------
参数:无,无
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | [(1, 0)]
2 | 2
[(2, 0), (2, 1)] | [(2, 0), (2, 1)]
-------------------------------------------------------------------------------------
参数:无,全局()
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | [(1, 0)]
2 | 2
[(2, 0), (2, 1)] | [(2, 0), (2, 1)]
-------------------------------------------------------------------------------------
参数:本地人(),无
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | [(1, 0)]
2 | 2
[(2, 0), (2, 1)] | [(2, 0), (2, 1)]
-------------------------------------------------------------------------------------
参数: {},无
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | [(1, 0)]
2 | 2
[(2, 0), (2, 1)] | [(2, 0), (2, 1)]
-------------------------------------------------------------------------------------
参数: {},{}
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | Traceback (most recent call last):
2 | File "<ipython-input-126-fe6125860589>", line 23, in <module>
[(2, 0), (2, 1)] | exec(code_str, param0, param1)
| File "<string>", line 5, in <module>
| File "<string>", line 5, in <listcomp>
| NameError: name 'i' is not defined
-------------------------------------------------------------------------------------
参数:无,{}
-------------------------------------------------------------------------------------
Exec output: | Exec output:
0 | 0
[] | []
1 | 1
[(1, 0)] | Traceback (most recent call last):
2 | File "<ipython-input-126-fe6125860589>", line 23, in <module>
[(2, 0), (2, 1)] | exec(code_str, param0, param1)
| File "<string>", line 5, in <module>
| File "<string>", line 5, in <listcomp>
| NameError: name 'i' is not defined