What is an alternative to execfile in Python 3?


Question

It seems they canceled in Python 3 all the easy way to quickly load a script by removing execfile()

Is there an obvious alternative I'm missing?

1
311
1/15/2017 6:15:44 AM

Accepted Answer

According to the documentation, instead of

execfile("./filename") 

Use

exec(open("./filename").read())

See:

340
2/2/2018 2:27:32 AM

You are just supposed to read the file and exec the code yourself. 2to3 current replaces

execfile("somefile.py", global_vars, local_vars)

as

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)

See:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon