简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM