2

This question is in relation to:

python, subprocess: reading output from subprocess

If P is a subprocess started with a command along the lines of

import subprocess

P = subprocess.Popen ("command", stdout=subprocess.PIPE)

we can read the output P produces by P.stdout.readline (). This is a blocking read though. How can I check if there is output ready for reading (without blocking)?

Community
  • 1
  • 1
kasterma
  • 4,259
  • 1
  • 20
  • 27
  • possible duplicate of [Non-blocking read on a stream in python.](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python) – Katriel Nov 15 '10 at 22:46
  • Following on SO: - https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python – pyfunc Nov 15 '10 at 22:39

1 Answers1

0

If you are using *nix, then you can use the select module to poll the stdout file descriptor

import subprocess
import select
poller = select.epoll()

P = subprocess.Popen ("command", stdout=subprocess.PIPE)
poller.register(P.stdout, select.EPOLLHUP)

while True:
    #block indefinitely: timeout = -1
    #return immediately: timeout = 0
    for fd, flags in poller.poll(timeout=0)
        foo = P.stdout.readline()
    #do something else before the next poll
Jeremy Brown
  • 17,880
  • 4
  • 35
  • 28