Search code examples
pythontimesubprocessstdoutstderr

Output of subprocess gets appended to file before time


I'm using subprocess to output std output and std error to their respective files. When I try to output time to both files before the respective messages, it is being written at the end.

Below is the code

import time
from subprocess import call

datetime_log = time.strftime("%Y-%m-%d %H:%M:%S")
with open("stdout.txt","ab") as stdout_file, open("stderr.txt","ab") as stderr_file:
    stdout_file.write(datetime_log + '\n'); stderr_file.write(datetime_log + '\n')
    call(['ls'], stdout = stdout_file, stderr = stderr_file)

The output of stdout.txt is:

pyshell1.py
pyshell2.py
stderr.txt
stdout.txt
2019-03-11 17:59:48
pyshell1.py
pyshell2.py
stderr.txt
stdout.txt
2019-03-11 18:06:17

How do I print the time before the output of ls subprocess command.


Solution

  • You need to flush the buffer:

    stdout_file.write(datetime_log + '\n')
    stderr_file.write(datetime_log + '\n')
    stdout_file.flush()
    stderr_file.flush()
    call(['ls'], stdout=stdout_file, stderr=stderr_file)