将stdout从subprocess.Popen保存到文件,以及向文件中写入更多内容 [英] Saving stdout from subprocess.Popen to file, plus writing more stuff to the file

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

问题描述

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

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的stdout刷新到日志中?还有一件可能相关的事情:可执行文件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.

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

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