Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to execfile in Python 3? [duplicate]

Python 2 had the builtin function execfile, which was removed in Python 3.0. This question discusses alternatives for Python 3.0, but some considerable changes have been made since Python 3.0.

What is the best alternative to execfile for Python 3.2, and future Python 3.x versions?

like image 366
Matt Joiner Avatar asked Jun 15 '11 12:06

Matt Joiner


People also ask

What is an alternative to Execfile in Python 3?

read()) is often given as an alternative to execfile("filename") , it misses important details that execfile supported. The following function for Python3. x is as close as I could get to having the same behavior as executing a file directly. That matches running python /path/to/somefile.py .

What is Python Execfile?

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


1 Answers

The 2to3 script replaces

execfile(filename, globals, locals) 

by

exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals) 

This seems to be the official recommendation. You may want to use a with block to ensure that the file is promptly closed again:

with open(filename, "rb") as source_file:     code = compile(source_file.read(), filename, "exec") exec(code, globals, locals) 

You can omit the globals and locals arguments to execute the file in the current scope, or use exec(code, {}) to use a new temporary dictionary as both the globals and locals dictionary, effectively executing the file in a new temporary scope.

like image 177
Sven Marnach Avatar answered Oct 03 '22 04:10

Sven Marnach