My module path = "..\blah\blah\myfolder\mymodule.py"
contains:
print('hi')
Code execution:
exec(compile(open(path, 'rb').read(), path, 'exec'))
and
exec(open(path, 'rb').read())
give the same result.
Why is compile()
needed?
My module path = "..\blah\blah\myfolder\mymodule.py"
contains:
print('hi')
Code execution:
exec(compile(open(path, 'rb').read(), path, 'exec'))
and
exec(open(path, 'rb').read())
give the same result.
Why is compile()
needed?
They are identical in your case, i.e. exec
and eval
use compile
if get the string as an input. But compile
can be used to precompile the code that will be repeatedly executed with exec
(or eval
), making it run faster because you don't need to compile the code each time. Consider:
compiled_code = compile(open(path, 'rb').read(), path, 'exec')
for _ in range(10**9):
exec(compiled_code)