Python3 Exec, Why Returns None?
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 'res
Solution 1:
The problem of course is not only that print
returns None
, it is that exec returns None, always.
>>> exec('42') isNoneTrue
If you'd need the return value, you'd use eval
:
>>>eval('42')
42
after which you'd notice that print
still returns None
...
Solution 2:
Thank you all decided as follows:
import sys
from io import StringIO
from contextlib import contextmanager
@contextmanagerdefstdoutIO(stdout=None):
old = sys.stdout
if stdout isNone:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
with stdoutIO() as s:
withopen('exx.py', 'rb') as file:
ff = compile(file.read(), 'exx.py', 'exec')
exec(ff, locals())
if'result'inlocals():
sys.stdout.write(locals().get('result'))
print(s.getvalue())
Solution 3:
Print always returns none.
Also this is not how you should ever execute code from another module. That's what import is for.
Post a Comment for "Python3 Exec, Why Returns None?"