Repost: execfile() confusion

Nathaniel Gray n8gray at caltech.edu.is.my.e-mail.address.com
Fri Sep 28 20:27:25 EDT 2001


Petr Kubanek wrote:

> 
> What's happen, if you use global in test2.py?

But I don't want x to be global.  It should be local to test.doit.

> 
> x is local to test2.py.

Yes, but I believe execfile is supposed to act on the locals in test.doit.  
That is, the locals of test2.py should be the same as the locals of test.doit 
when I execfile( 'test2.py' ) in that context.
 
>From the documentation:
execfile(...)
    execfile(filename[, globals[, locals]])
 
    Read and execute a Python script from a file.
    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.

In "the current globals and locals", which in my case are the locals and 
globals of test.doit, x is undefined, but after test2.py is execfiled it should 
be defined as 'spam' in the locals of test.doit.  At least that's how I think 
it should work.  Since it doesn't seem to *actually* work that way I could 
certainly be wrong!  I'd sure appreciate it if somebody would explain to me how 
it *does* work, though.

> Another possibility is to use __main__ module. But these is now depreciated.

I really just want to understand what execfile does, since it doesn't seem to 
do what I thought it did.

-- 
Nathaniel Gray

California Institute of Technology
Computation and Neural Systems
--




More information about the Python-list mailing list