使用 python Popen 读取最后一行 [英] Using python Popen to read the last line

查看:91
本文介绍了使用 python Popen 读取最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的python程序:

I have a simple python program:

test.py:

import time
for i in range(100000):
    print i
    time.sleep(0.5)

我想使用另一个执行上述程序的程序,以便在上述程序计数时读取最后一行输出.

I want to use another program that executes the above one in order to read the last line output while the above program is counting.

import subprocess

process = subprocess.Popen("test",stdout=PIPE)
sleep(20) # sleeps an arbitrary time
print stdout.readlines()[-1]

问题是 process.stdout.readlines() 一直等到 test.py 完成执行.有什么办法可以在程序执行时读取输出中写入的最后一行吗?

The problem is that process.stdout.readlines() waits until test.py finishes execution. Is there any way to read the last line that has been writen in the output while the program is executing?

推荐答案

您可以使用 collections.deque 只保存最后指定的行数:

You could use collections.deque to save only the last specified number of lines:

#!/usr/bin/env python
import collections
import subprocess
import time
import threading

def read_output(process, append):
    for line in iter(process.stdout.readline, ""):
        append(line)

def main():
    process = subprocess.Popen(["program"], stdout=subprocess.PIPE)
    # save last `number_of_lines` lines of the process output
    number_of_lines = 1
    q = collections.deque(maxlen=number_of_lines)
    t = threading.Thread(target=read_output, args=(process, q.append))
    t.daemon = True
    t.start()
    #
    time.sleep(20)

    # print saved lines
    print ''.join(q),
    # process is still running
    # uncomment if you don't want to wait for the process to complete
    ##process.terminate() # if it doesn't terminate; use process.kill()
    process.wait()

if __name__=="__main__":
    main()

请参阅其他仅打印输出部分的类似尾部的解决方案

如果您的子程序在运行时对其标准输出使用块缓冲(而不是行缓冲),请参见此处非交互式.

这篇关于使用 python Popen 读取最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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