Reputation: 29
I have a script that starts several processes with subprocess. Now I want to write a log file, that contains my own output and the output of the sub processes.
log = open(LOG,'w')
for tasks in tasklist:
log.write('log text')
... some code and log text ...
sp = subprocess('task[0]',stdout=log)
sp.wait()
log.write('log text')
sp = subprocess('task[1]',stdout=log)
sp.wait()
log.write('log text')
sp = subprocess('task[2]',stdout=log)
sp.wait()
log.write('log text')
Right now it writes the output of subprocess to the top and then everything I wrote. Is ther any better way then to close and reopen the file every time before I start subprocess?
Upvotes: 3
Views: 74
Reputation: 1122102
You need to flush the python buffers on each write:
log.write('log text')
log.flush()
The subprocesses do not buffer their writes, so their data ends up in the logfiles before whatever python wrote. Python's writes end up in it's buffer and are not flushed until that buffer is full.
Upvotes: 2