Execute commands from file
Martin Blume
mblume at socha.net
Thu May 17 12:11:05 EDT 2007
"Steve Holden" schrieb
> >>
> >> Try it on a file that reads something like
> >>
> >> xxx = 42
> >> print xxx
> >>
> >> and you will see NameError raised because the assignment
> >> hasn't affected the environment for the print statement.
> >>
> > [...]
> >
> No, because there isn't one. Now try adding a function
> definition and see how well it works.
>
C:\temp>more question.py
xxx=42
print xxx
def sowhat():
print xxx
print xxx
C:\temp>c:\programme\python\python
Python 2.4 (#60, Nov 30 2004, 11:49:19)
[MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information.
>>> exec open("question.py").read()
42
42
>>> sowhat()
42
>>> xxx
42
Seems to work great to me.
OTOH, this doesn't:
>>> inp=open("question.py")
>>> for l in inp:
... exec l
...
42
Traceback (most recent call last):
File "<stdin>", line 2, in ?
File "<string>", line 1
def sowhat():
^
SyntaxError: unexpected EOF while parsing
So it seems to depend on the way the file is read.
Regards
Martin
More information about the Python-list
mailing list