我有一个简单的python程序:
test.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完成执行。
有没有办法在程序执行时读取输出中写入的最后一行?
答案 0 :(得分:2)
您可以使用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如果您的子程序在非交互式运行时对其标准输出使用块缓冲(而不是行缓冲)。
答案 1 :(得分:0)
使用sh.py非常微不足道:
import sh
def process_line(line):
print line
process = sh.python("test.py", _out=process_line)
process.wait()