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

标签 python time subprocess stdout stderr

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

下面是代码

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/

相关文章:

python - 重定向 stdout 时在 python 上调用子进程时出错

python - 是否可以根据批处理标签(y_true)分布更新每批处理的学习率?

python - pbkdf2 和哈希比较

time - VB6 应用时序

c++ - 如何将时间转换为纪元时间?

Python popen() - 通信(str.encode(编码 ="utf-8",错误 ="ignore"))崩溃

python - 在 Django 中抛出自定义异常时异常值字段为空

python - Opencv:使用 FAST 关键点和 BRIEF 特征训练 SVM

php - 文章 :published_time date format

python - 猫 : invalid option -- 'F' error trying to run linux command from python subprocess