pythonstdoutpopenptypeek

Python: How to peek into a pty object to avoid blocking?


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.


Solution

  • Yes, use the select module's poll:

    import select
    q = select.poll()
    q.register(stdout,select.POLLIN)
    

    and in the while use:

    l = q.poll(0)
    if not l:
        pass # no input
    else:
        pass # there is some input