Problem with select.poll and popen2

Magnus Lycka lycka at carmen.se
Tue Aug 30 11:56:57 EDT 2005


Magnus Lycka wrote:
> I'm trying to read standard out in a process started with popen2
> in a non-blocking way. (Other good ways of doing this than the
> one I tried are appreciated.)

I'm starting to get on top of this. First of all, I was confused
by POLLIN and POLLOUT, since it's IN or OUT of the polling process,
so we want the POLLIN filter for the output of the spawned process...

Secondly, I thought that I'd get a fd, event pair for each kind of
event, but events are bitwise ORed together, and in my dumb downed
version I had used a command (date) that ends quickly, and then there
is a stream of POLLHUP that comes out of poll, even though I didn't
register for that. (Is it supposed to be like that?)

The following pair of programs (sender.py first) seems to behave as
I intended. Perhaps they can be of use for someone. After all, it's
not only sockets that we might want to read in an unblocking way,
but it seems most examples are geared towards that.


import time, sys
while 1:
     print 'HELLO'
     sys.stdout.flush()
     time.sleep(2)

....

import sys
import select
import os

CMD = 'python sender.py'

fi, fo = os.popen2(CMD)
fi.close()
p = select.poll()
p.register(fo, select.POLLIN)
while 1:
     l = p.poll(500)
     for (o, evt) in l:
	if o == fo.fileno() and evt & select.POLLIN:
             c = fo.read(10)
             print c,
     else:
         print "Timeout!"




More information about the Python-list mailing list