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?
While exec(open("filename").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
.
def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)
# execute the file
execfile("/path/to/somefile.py")
Notes:
__main__
, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
__file__
is nicer for exception messages and some scripts use __file__
to get the paths of other files relative to them.Takes optional globals & locals arguments, modifying them in-place as execfile
does - so you can access any variables defined by reading back the variables after running.
Unlike Python2's execfile
this does not modify the current namespace by default. For that you have to explicitly pass in globals()
& locals()
.