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?
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?
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:
You could write your own function:
def xfile(afile, globalz=None, localz=None):
with open(afile, "r") as fh:
exec(fh.read(), globalz, localz)
If you really needed to...
If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?
If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.
>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'
test.py:
def run():
return "Hello world!"
If you're using Python 3.1 or later, you should also take a look at importlib.
Avoid exec() if you can. For most applications, it's cleaner to make use of Python's import system.
This function uses built-in importlib to execute a file as an actual module:
from importlib import util
def load_file_as_module(name, location):
spec = util.spec_from_file_location(name, location)
module = util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
Let's have a file foo.py:
def hello():
return 'hi from module!'
print('imported from', __file__, 'as', __name__)
And import it as a regular module:
>>> mod = load_file_as_module('mymodule', './foo.py')
imported from /tmp/foo.py as mymodule
>>> mod.hello()
hi from module!
>>> type(mod)
<class 'module'>
This approach doesn't pollute namespaces or messes with your $PATH whereas exec() runs code directly in the context of the current function, potentially causing name collisions. Also, module attributes like __file__ and __name__ will be set correctly, and code locations are preserved. So, if you've attached a debugger or if the module raises an exception, you will get usable tracebacks.
Note that one minor difference from static imports is that the module gets imported (executed) every time you run load_file_as_module(), and not just once as with the import keyword.