Execute commands from file

Maric Michaud maric at aristote.info
Thu May 17 12:03:29 EDT 2007


Steve Holden a écrit :
> 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
>>> 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
>>>
>> 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

This is just a problem with indentation and blocks of code, the
followong will do :

commands = open("commands")
namespace, block = {}, ""
for line in commands :
     line=line[:-1]
     if not line : continue
     if line[0].isspace() :
         block += '\n' + line
         continue
     else :
         if block.strip() :
             exec block in namespace
         block = line

exec block in namespace
print dict((k, v) for k, v in namespace.items() if k != "__builtins__")


with commands containing  :

"""

x = 5

def toto(arg) :
     print arg

     def inner() :
         print arg*arg

     inner()


toto(x)
"""

output :
5
25
{'x': 5, 'toto': <function toto at 0x01D30C70>}



(sorry Steve for the private mail)

-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21




More information about the Python-list mailing list