Skip to content Skip to sidebar Skip to footer

Using Python Popen To Read The Last Line

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

Solution 1:

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

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

defread_output(process, append):
    for line initer(process.stdout.readline, ""):
        append(line)

defmain():
    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 linesprint''.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()

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

See here if your child program uses a block-buffering (instead of line-bufferring) for its stdout while running non-interactively.

Solution 2:

Fairly trivial with sh.py:

import sh

defprocess_line(line):
    print line

process = sh.python("test.py", _out=process_line)
process.wait()

Post a Comment for "Using Python Popen To Read The Last Line"