Python3 exec, why returns None?

六眼飞鱼酱① 提交于 2021-02-04 08:32:26

问题


When the code below this text, and returns the result None why?

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:

print('777777')

回答1:


The problem of course is not only that print returns None, it is that exec returns None, always.

>>> exec('42') is None
True

If you'd need the return value, you'd use eval:

>>> eval('42')
42

after which you'd notice that print still returns None...




回答2:


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())



回答3:


Print always returns none.

Also this is not how you should ever execute code from another module. That's what import is for.



来源:https://stackoverflow.com/questions/29592588/python3-exec-why-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!