#!/usr/bin/python from __future__ import print_function import subprocess import select # can even be wrapped without change by "stdbuf -oL sh -c ..." PROG = """ echo 'xxxxxxxxxxxx' echo 'yyyyyyyyyyyyyyy' read something echo 'aaaaaaaa' echo 'bbbbbbbb' echo 'cccccccc' echo 'dddddddd' echo 'FINISHED' read something """ process = subprocess.Popen( PROG, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, # python2 default, broken since 3.3.1 ? universal_newlines=True) poll = select.poll() poll.register(process.stdout, select.POLLIN|select.POLLHUP|select.POLLERR) process.stdin.write("go\n") while True: matches = poll.poll() if not matches: continue for fd, event in matches: if event & select.POLLIN: l = process.stdout.readline().strip() print(">" + l) if l == "FINISHED": process.stdin.write("quit\n") if event & select.POLLHUP: print("pipe closed") exit(0) if event & select.POLLERR: print("process error") exit(1)