How to eval a file
Björn Lindberg
d95-bli at nada.kth.se
Sun Feb 23 08:42:34 EST 2003
bokr at oz.net (Bengt Richter) writes:
> If you'd posted a minimal example of what you did "without success,"
> with copy/paste of the screen interaction and/or test run, I'd bet you
> would know by now how to make it work ;-)
I tried something like this:
class C:
def m(self):
execfile("../collection/collection.layout")
self.collection = collection
def n(self):
return self.collection
c = C()
c.m()
print c.n()
File "/tmp/python-2494uy", line 6, in m
self.collection = collection
NameError: global name 'collection' is not defined
>>>
The file has a line with "collection = 'bla, bla....'" in it.
> 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.
So, if the globals and locals arguments defaults to the current scope,
why don't I have a global variable 'collection' when the execfile returns?
However, if I include a dictionary as a second argument to execfile(),
I can extract 'collection' from it, and it works like expected.
Björn
More information about the Python-list
mailing list