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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With