Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an alternative to execfile in Python 3?

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?

like image 226
R S Avatar asked Jan 12 '09 17:01

R S


People also ask

What is Python Execfile?

A file to be parsed and evaluated as a sequence of Python statements (similarly to a module). globals.


2 Answers

According to the documentation, instead of

execfile("./filename")  

Use

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

See:

  • What’s New In Python 3.0
like image 134
Pedro Vagner Avatar answered Oct 05 '22 23:10

Pedro Vagner


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:

  • http://docs.python.org/release/2.7.3/library/functions.html#execfile
  • http://docs.python.org/release/3.2.3/library/functions.html#compile
  • http://docs.python.org/release/3.2.3/library/functions.html#exec
like image 42
Benjamin Peterson Avatar answered Oct 06 '22 00:10

Benjamin Peterson