It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload().
Is there an obvious alternative I'm missing?
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload().
Is there an obvious alternative I'm missing?
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!"
Finally, it's worth noting that importlib looks likely to be included in 3.1, though that's kind of far-future right now.
def execfile(file, globals=globals(), locals=locals()):
with open(file, "r") as fh:
exec(fh.read()+"\n", globals, locals)
If you really needed to...
If you have to use execfile
, you have a design problem.
Of course you can always read the entire file as a string and use the exec
statement on it. But it would be even better to rethink your application's design so you won't need it in first place.
You are just supposed to read the file and exec the code yourself. 2to3 current replaces
execfile("somefile.py", local_vars, global_vars)
as
exec(compile(open("somefile.py").read(), "somefile.py", 'exec'), local_vars, global_vars)
(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)
This one is better, since it takes the globals and locals from the caller:
import sys
def execfile(filename, globals=None, locals=None):
if globals is None:
globals = sys._getframe(1).f_globals
if locals is None:
locals = sys._getframe(1).f_locals
with open(filename, "r") as fh:
exec(fh.read()+"\n", globals, locals)