Subject: Execfile() - bug / strange behavior - DN [1]


amitp@Xenon.Stanford.EDU (Amit Patel) - 04 Feb 2000 - comp.lang.python

 I'm trying to understand why execfile(fn) is different from exec
 open(fn,'r').read().  Here's my program:

 ====
 def timbot():
     a = 3
     execfile("1.txt")
     print a
     print locals()

 timbot()
 ====

 Then I have 1.txt:

 ====
 a = 5
 b = 8
 ====

 When I run this, I expect to see a is 5, but I get:

 ====
 3
 {'b': 8, 'a': 3}
 ====

 I don't understand why variable a is not set, but b is!  Even
 stranger, when I try to print b from timbot(), it gives me NameError,
 even though it's in locals()!

 When I change execfile("1.txt") to exec open("1.txt",'r').read(), it
 works just fine!

 This seems to be different from any recent execfile bugs I can find on
 Deja, but it sounds like it could be the the same as a bug reported in
 **1996** (egads! Was Tim even a bot back then? Did we even have 1.5?):

 http://www.deja.com/getdoc.xp?AN=145064312&fmt=text

 Any ideas?  Either why it's still a bug or what I'm doing wrong or why
 the documentation is misleading ..?

     - Amit

 [In case anyone is wondering, this is Python 1.5.2 for Linux, from RH 6.1]

Last modified
2000-03-11

(195.108.246.55)

Note: you are looking at
the snapshot of an old wiki
- much of this information
is likely to be very outdated