Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why subprocess stdout to a file is written out of order?

I have a python script that calls an executable. The executable's output is redirected to a log file along with some info about the time it was called. For example, using python -V as the executable to illustrate:

import time, subprocess
with open('./LOGFILE.txt', 'a') as F:
    F.write('******\n')
    F.write('Events on %s :\n'%time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    EXE_output = subprocess.call(['python', '-V'], stdout=F, stderr=F)

The output of the file LOGFILE.txt is:

Python 2.7.3
******
Events on 2013-04-10 19:27:25 :

Where I was expecting it as follows:

******
Events on 2013-04-10 19:27:25 :
Python 2.7.3

I wrote the ****** and time info in the opened log file before running the subprocess and redirecting its output and error into the file. Why is ordering like that? and how can I reorder?

like image 304
amyassin Avatar asked Apr 10 '13 16:04

amyassin


1 Answers

You should call F.flush() before running the subprocess. The reason for this is that the subprocess will flush the buffers when it finishes, whereas you are not.

like image 104
gcbirzan Avatar answered Sep 24 '22 03:09

gcbirzan