子进程的输出在时间之前附加到文件

Output of subprocess gets appended to file before time

我正在使用子进程将标准输出和标准错误输出到它们各自的文件。当我尝试在各自的消息之前将时间输出到两个文件时,它被写在最后。

下面是代码

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)

stdout.txt的输出是:

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

如何打印 ls 子进程命令输出之前的时间。

您需要刷新缓冲区:

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)