在运行时获取进程的输出 [英] Getting output of a process at runtime

查看:36
本文介绍了在运行时获取进程的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 脚本来运行使用 subprocess.Popen 的进程,同时将输出存储在文本文件中并在控制台上打印.这是我的代码:

I am using a python script to run a process using subprocess.Popen and simultaneously store the output in a text file as well as print it on the console. This is my code:

result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in result.stdout.readlines(): #read and store result in log file
    openfile.write("%s\n" %line)
    print("%s" %line)

上面的代码工作正常,但它首先完成过程并将输出存储在 result 变量中.之后 for 循环 存储输出并打印它.

Above code works fine, but what it does is it first completes the process and stores the output in result variable. After that for loop stores the output as well as print it.

但我希望在运行时输出(因为我的过程可能需要几个小时才能完成,我在所有这些小时内都没有得到任何输出).

But i want the output at runtime (as my process can take hours to complete, i don't get any output for all these hours).

那么有没有其他函数可以动态地(在运行时)给我输出,这意味着只要进程给出第一行,它就应该被打印出来.

So is there any other function that gives me the output dynamically (at runtime), means as soon as the process gives first line, it should get printed.

推荐答案

这里的问题是 .readlines() 在返回之前获取整个输出,因为它构造了一个完整的列表.直接迭代即可:

The problem here is that .readlines() gets the entire output before returning, as it constructs a full list. Just iterate directly:

for line in result.stdout:
    print line

这篇关于在运行时获取进程的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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