Execute commands from file

Steve Holden steve at holdenweb.com
Thu May 17 10:48:03 EDT 2007


i3dmaster wrote:
> On May 16, 1:05 pm, Steve Holden <s... at holdenweb.com> wrote:
>> Martin Blume wrote:
>>> "tmp123" schrieb >
>>>> We have very big files with python commands
>>>> (more or less, 500000 commands each file).
>>>> It is possible to execute them command by command,
>>> inp = open(cmd_file)
>>> for line in inp:
>>>     exec line
>>> might help. You don't get quite the same feeling as
>>> "like if the commands was typed one after the other
>>> in a interactive session", but perhaps this helps.
>>> Warning: the code above is without any error checks.
>>> You might also run into security problems, the example
>>> above assumes you trust your input.
>>> HTH. YMMV.
>>> Martin
>> The problem with this approach is that each line executes without any
>> connection to the environment created by previous lies.
>>
>> 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.
>>
>> 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 ----------------
> 
> cat file:
> 
> x = 100
> print x
> 
> cat file.py:
> #!/usr/bin/python2.4
> 
> import os.path
> import sys
> 
> file, ext = os.path.splitext(sys.argv[0])
> f = open(file,'rb')
> for i in f:
>         exec i
> 
>> ./file.py
> 100
> 
> Don't see the problem though.
> 
No, because there isn't one. Now try adding a function definition and 
see how well it works.

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