Execute commands from file
Steve Holden
steve at holdenweb.com
Thu May 17 17:46:55 EDT 2007
Martin Blume wrote:
> "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.
>
It depends on the way the lines of the file are executed, not how they
are read. And you may remember the original poster was proposing this:
inp = open(cmd_file)
> for line in inp:
> exec line
As for your first example, why not just use execfile() ?
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com squidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------
More information about the Python-list
mailing list