Alternative to execfile in Python 3?

Alternative to execfile in Python 3?

The 2to3 script replaces

execfile(filename, globals, locals)


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(, 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.


can be replaced with


which works in all versions of Python

Newer versions of Python will warn you that you didnt close that file, so then you can do this is you want to get rid of that warning:

with open(filename) as infile:

But really, if you care about closing files, you should care enough to not use exec in the first place.

Alternative to execfile in Python 3?

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


  • 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):
    global_namespace = {
        __file__: filepath,
        __name__: __main__,
    with open(filepath, rb) as file:
        exec(compile(, filepath, exec), global_namespace)

# Execute the file.

Leave a Reply

Your email address will not be published. Required fields are marked *