0
votes

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')
3
Try print( print('777777') ) - Eric Levieil
None as opposed to... what? What were you expecting? As it stands, that's not even valid syntax. - jonrsharpe
Returns the same thing: print(exec(open ( 'exx.py').read())) - Strelok2014Strelok

3 Answers

6
votes

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...

0
votes

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

Print always returns none.

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