[英]Python3 exec, why returns None?
When the code below this text, and returns the result None why?当这段文字下面的代码,并返回结果 None 为什么?
with open('exx.py', 'rb') as file:
ff = compile(file.read(), 'exx.py', 'exec')
snip_run = exec(ff, locals())
if 'result' in locals():
print(snip_run, result)
else:
print(snip_run)
Result:结果:
777777
None
Module code exx.py:模块代码 exx.py:
print('777777')
The problem of course is not only that print
returns None
, it is that exec returns None , always.当然,问题不仅在于print
返回None
,还在于exec始终返回 None 。
>>> exec('42') is None
True
If you'd need the return value, you'd use eval
:如果您需要返回值,您可以使用eval
:
>>> eval('42')
42
after which you'd notice that print
still returns None
...之后你会注意到print
仍然返回None
...
Thank you all decided as follows:谢谢大家决定如下:
import sys
from io import StringIO
from contextlib import contextmanager
@contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
with stdoutIO() as s:
with open('exx.py', 'rb') as file:
ff = compile(file.read(), 'exx.py', 'exec')
exec(ff, locals())
if 'result' in locals():
sys.stdout.write(locals().get('result'))
print(s.getvalue())
Print always returns none.打印总是不返回。
Also this is not how you should ever execute code from another module.此外,这也不是您应该从另一个模块执行代码的方式。 That's what import is for.这就是导入的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.