I am using pty
to read non blocking the stdout of a process like this:
import os
import pty
import subprocess
master, slave = pty.openpty()
p = subprocess.Popen(cmd, stdout = slave)
stdout = os.fdopen(master)
while True:
if p.poll() != None:
break
print stdout.readline()
stdout.close()
Everything works fine except that the while-loop
occasionally blocks. This is due to the fact that the line print stdout.readline()
is waiting for something to be read from stdout
. But if the program already terminated, my little script up there will hang forever.
My question is: Is there a way to peek into the stdout
object and check if there is data available to be read? If this is not the case it should continue through the while-loop
where it will discover that the process actually already terminated and break the loop.
The select.poll() answer is very neat, but doesn't work on Windows. The following solution is an alternative. It doesn't allow you to peek stdout, but provides a non-blocking alternative to readline() and is based on this answer:
Other solutions for non-blocking read have been proposed here, but did not work for me:
Yes, use the select module's poll:
and in the while use: