3

我有一个简单的python程序:

测试.py:

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

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

import subprocess

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

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

4

2 回答 2

3

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

#!/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()

查看仅打印输出部分的其他类似尾巴的解决方案

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

于 2012-11-11T14:30:39.813 回答
1

sh.py相当简单:

import sh

def process_line(line):
    print line

process = sh.python("test.py", _out=process_line)
process.wait()
于 2012-11-12T06:02:14.763 回答