views:

3297

answers:

5

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?

+6  A: 

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.

ascobol
+4  A: 
def execfile(file, globals=globals(), locals=locals()):
    with open(file, "r") as fh:
        exec(fh.read()+"\n", globals, locals)

If you really needed to...

Evan Fosmark
+1, but the example should probably use 'with fh=open(...):'
orip
@orip: No, it shouldn't. You can't have assignment in an expression in python.
nosklo
-1: the exec statment doesn't work this way. Code doesn't run in any version of python.
nosklo
-1: Not reliable. Some uses of execfile are incompatible.
Brian
A: 

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.

nosklo
The problem is of course that I don't have an application, I am doing interactive research. I need to write quick functions and check them in the interpreter quickly...
R S
Some interactive applications (with a python prompt) use execfile as the main way to load up the next job description file, for example CERN's ganga.
kaizer.se
+3  A: 

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.)

Benjamin Peterson
This works for me. However, I noticed that you've written the local and global arguments in the wrong order. It's actually: exec(object[, globals[, locals]]). Of course if you had the arguments flipped in the original, then 2to3 will produce exactly what you said. :)
Nathan Sanders
A: 

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)
Noam