Repost: execfile() confusion

Nathaniel Gray n8gray at caltech.edu.is.my.e-mail.address.com
Fri Sep 28 21:18:45 CEST 2001


Sorry for the repost but I didn't get any responses.  
So once again, execfile() isn't doing what I thought it did.

For example, with these two files:

##############
#### test2.py ####
x = 'spam'

#### test.py ####
def doit():
    execfile( 'test2.py' ) # x = 'spam'
    print x
    
doit()
##############

I get the following when I run 'python test.py':
"""
Traceback (most recent call last):
  File "test.py", line 5, in ?
    doit()
  File "test.py", line 3, in doit
    print x
NameError: global name 'x' is not defined
"""

I though that execfile was supposed to act on the locals() of the scope 
from which it was called.  I also tried adding x=None to the top of doit() 
but execfile still doesn't change its value to 'spam'.  Can somebody please 
explain what's going on?

Thanks a lot,
-Nathan 
n8gray at caltech dot e d u






More information about the Python-list mailing list