[Tutor] eval use (directly by interpreter vs with in a script)

Steven D'Aprano steve at pearwood.info
Tue Nov 4 02:55:35 CET 2014


On Sun, Nov 02, 2014 at 06:23:12PM -0500, Ken G. wrote:

> I use exec to jump to another program within the
> same directory, such as:
> 
> execfile("BloodPressure02Sorting.py")
> 
> and let the program terminate there. Should I do
> it differently or are you talking about a different
> horse?

That's an interesting use of execfile, but I think there's a slight 
misconception. The program doesn't terminate "there" (inside the other 
script), it terminates in the original script, after the execfile() 
function has returned. You can see this if you make a wrapper script 
like this:


print "inside wrapper script"
execfile("/path/to/script/you/want/to/run.py")
print "still inside the wrapper script"


provided the run.py script has no fatal errors, you will see the second 
print line as well as the first.

In fact, execfile doesn't merely execute the other script, it executes 
it *inside the current namespace*. Let me explain.

"Namespace" is the technical name for a collection of variables. 
Different places in your code have different variables. Every function 
has its own independent set of local variables, so each function is a 
namespace. Local variables inside one function don't affect local 
variables inside another.

Global variables also live in their own namespace. Normally, each .py 
file is its own namespace, but using execfile is special: rather than 
executing the script in its own namespace, by default it is executed 
in the current namespace.

Try this:

# File run.py
x = 42


# File wrapper.py
x = 23
execfile("run.py")
print x


Running wrapper.py should print 42, not 23.

Normally, that sort of behavious is not what you want. You want other 
scripts to be independent of the current script, so that you can use 
each of them independently. To give an analogy: your screwdriver 
shouldn't suddenly stop working because you've picked up a hammer.

execfile() is useful in the interactive interpreter, but to my mind if 
you want to run BloodPressure02Sorting.py you should just run that file. 
If you are using Linux, probably the easiest way is to have a shell open 
and just enter this:

python BloodPressure02Sorting.py

from the directory containing the script. Many Linux GUI environments, 
like KDE, will also have a "Run command" item under the Start menu.


-- 
Steven


More information about the Tutor mailing list