将标准输出从 subprocess.Popen 保存到文件,并将更多内容写入文件 [英] Saving stdout from subprocess.Popen to file, plus writing more stuff to the file

查看:115
本文介绍了将标准输出从 subprocess.Popen 保存到文件,并将更多内容写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 python 脚本,它使用 subprocess.Popen 来执行两个程序(来自已编译的 C 代码),每个程序都会产生标准输出.该脚本获取该输出并将其保存到文件中.因为输出有时大到足以压倒 subprocess.PIPE,导致脚本挂起,所以我将 stdout 直接发送到日志文件.我想让我的脚本在文件的开头和结尾以及两个 subprocess.Popen 调用之间写一些东西.但是,当我查看日志文件时,我从脚本写入日志文件的所有内容都放在文件的顶部,然后是所有可执行的标准输出.如何将添加的文本交错到文件中?

I'm writing a python script that uses subprocess.Popen to execute two programs (from compiled C code) which each produce stdout. The script gets that output and saves it to a file. Because the output is sometimes large enough to overwhelm subprocess.PIPE, causing the script to hang, I send the stdout directly to the log file. I want to have my script write something to the beginning and end of the file, and between the two subprocess.Popen calls. However, when I look at my log file, anything I wrote to the log file from the script is all together at the top of the file, followed by all the executable stdout. How can I interleave my added text to the file?

def run(cmd, logfile):
    p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
    return p

def runTest(path, flags, name):
    log = open(name, "w")
    print >> log, "Calling executable A"
    a_ret = run(path + "executable_a_name" + flags, log)
    print >> log, "Calling executable B"
    b_ret = run(path + "executable_b_name" + flags, log)
    print >> log, "More stuff"
    log.close()

日志文件有:调用可执行文件 A调用可执行文件 B更多东西[...来自两个可执行文件的标准输出...]

The log file has: Calling executable A Calling executable B More stuff [... stdout from both executables ...]

例如,在调用 Popen 之后,有没有办法可以将 A 的标准输出刷新到日志中?还有一件可能相关的事情:可执行文件 A 开始,然后在 B 上挂起,在 B 打印内容并完成之后,A 然后打印更多内容并完成.

Is there a way I can flush A's stdout to the log after calling Popen, for example? One more thing that might be relevant: Executable A starts then pends on B, and after B prints stuff and finishes, A then prints more stuff and finishes.

我在 RHE Linux 上使用 Python 2.4.

I'm using Python 2.4 on RHE Linux.

推荐答案

您可以在每个 Popen 对象上调用 .wait() 以确保它已完成,然后调用 log.flush().也许是这样的:

You could call .wait() on each Popen object in order to be sure that it's finished and then call log.flush(). Maybe something like this:

def run(cmd, logfile):
    p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)
    ret_code = p.wait()
    logfile.flush()
    return ret_code

如果您需要与外部函数中的 Popen 对象进行交互,您可以将 .wait() 调用移到那里.

If you need to interact with the Popen object in your outer function you could move the .wait() call to there instead.

这篇关于将标准输出从 subprocess.Popen 保存到文件,并将更多内容写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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