我创建文件mymod.py:
def myfunc():
s = """
users = ['root','service']
flag = True
c_list_with_test = [ u for u in users if flag ]
print(c_list_with_test)
"""
exec(s)
print('ok')
使用python2没问题:
$ python2
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymod
>>> mymod.myfunc()
['root', 'service']
ok
但是使用python3列表理解测试变量是未定义的:
$ 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.
>>> import mymod
>>> mymod.myfunc()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/elapouya/tmp/mymod.py", line 8, in myfunc
exec(s)
File "<string>", line 4, in <module>
File "<string>", line 4, in <listcomp>
NameError: name 'flag' is not defined
>>>
为什么?解决方法是什么?
注意:如果我不使用import或exec,则一切正常。这确实是造成问题的组合import + exec。