我正在使用子进程将标准输出和标准错误输出到各自的文件。当我尝试在各自的消息之前将时间输出到两个文件时,它被写在最后。
下面是代码
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
subprocess 命令输出之前的时间。
最佳答案
您需要刷新缓冲区:
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)
关于python - 子进程的输出在时间之前附加到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55102247/