#!/usr/bin/env python
import os
import sys
from select import select
from subprocess import PIPE, Popen

# dummy process to generate some output with a delay
p = Popen([sys.executable, '-u', '-c', """import time
for i in range(5):
    print("%d" % i)
    time.sleep(.1)
"""], bufsize=0, stdout=PIPE)

# read input from the subprocess and stdin concurrently
timeout = .4 # seconds
rlist = [f.fileno() for f in [sys.stdin, p.stdout]]
while rlist: # while not EOF
    for fd in select(rlist, [], [], timeout)[0]:
        input_data = os.read(fd, 512)
        source = "stdin" if fd == sys.stdin.fileno() else "subprocess"
        print("got %r from %s" % (input_data, source))
        if not input_data: # EOF
            rlist.remove(fd)
p.stdout.close()
p.wait()