When the code below this text, and returns the result None why?
JavaScript
x
8
1
with open('exx.py', 'rb') as file:
2
ff = compile(file.read(), 'exx.py', 'exec')
3
snip_run = exec(ff, locals())
4
if 'result' in locals():
5
print(snip_run, result)
6
else:
7
print(snip_run)
8
Result:
JavaScript
1
3
1
777777
2
None
3
Module code exx.py:
JavaScript
1
2
1
print('777777')
2
Advertisement
Answer
The problem of course is not only that print
returns None
, it is that exec returns None, always.
JavaScript
1
3
1
>>> exec('42') is None
2
True
3
If you’d need the return value, you’d use eval
:
JavaScript
1
3
1
>>> eval('42')
2
42
3
after which you’d notice that print
still returns None
…