为什么子进程标准输出到文件被乱序写入? [英] Why subprocess stdout to a file is written out of order?

查看:57
本文介绍了为什么子进程标准输出到文件被乱序写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用可执行文件的 python 脚本.可执行文件的输出被重定向到一个日志文件以及一些关于它被调用的时间的信息.例如,使用python -V作为可执行文件来说明:

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)

文件LOGFILE.txt的输出是:

Python 2.7.3
******
Events on 2013-04-10 19:27:25 :

我期待的地方如下:

******
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?

推荐答案

您应该在运行子进程之前调用 F.flush().这样做的原因是子进程在完成时会刷新缓冲区,而您不会.

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.

这篇关于为什么子进程标准输出到文件被乱序写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆