Question

This question already has an answer here:

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?

Was it helpful?

Solution

The 2to3 script (also the one in Python 3.2) replaces

execfile(filename, globals, locals)

by

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

This seems to be the official recommendation.

OTHER TIPS

execfile(filename)

can be replaced with

exec(open(filename).read())

which works in all versions of Python

In Python3.x this is the closest thing I could come up with to executing a file directly, that matches running python /path/to/somefile.py.

Notes:

  • Uses binary reading to avoid encoding issues
  • Garenteed to close the file (Python3.x warns about this)
  • defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
  • setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them.
def exec_full(filepath):
    import os
    global_namespace = {
        "__file__": filepath,
        "__name__": "__main__",
    }
    with open(filepath, 'rb') as file:
        exec(compile(file.read(), filepath, 'exec'), global_namespace)

# execute the file
exec_full("/path/to/somefile.py")

Standard runpy.run_path is an alternative.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top