gpt4 book ai didi

python - 使用 python Popen 读取最后一行

转载 作者:行者123 更新时间:2023-12-04 03:03:41 25 4
gpt4 key购买 nike

我有一个简单的 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 完成执行。有没有办法在程序执行时读取输出中写入的最后一行?

最佳答案

您可以使用 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()

参见 other tail-like solutions that print only the portion of the output

See here如果您的子程序在非交互式运行时为其标准输出使用 block 缓冲(而不是行缓冲)。

关于python - 使用 python Popen 读取最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com