fork download
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. from select import select
  5. from subprocess import PIPE, Popen
  6.  
  7. # dummy process to generate some output with a delay
  8. p = Popen([sys.executable, '-u', '-c', """import time
  9. for i in range(5):
  10. print("%d" % i)
  11. time.sleep(.1)
  12. """], bufsize=0, stdout=PIPE)
  13.  
  14. # read input from the subprocess and stdin concurrently
  15. timeout = .4 # seconds
  16. rlist = [f.fileno() for f in [sys.stdin, p.stdout]]
  17. while rlist: # while not EOF
  18. for fd in select(rlist, [], [], timeout)[0]:
  19. input_data = os.read(fd, 512)
  20. source = "stdin" if fd == sys.stdin.fileno() else "subprocess"
  21. print("got %r from %s" % (input_data, source))
  22. if not input_data: # EOF
  23. rlist.remove(fd)
  24. p.stdout.close()
  25. p.wait()
Success #stdin #stdout 0.03s 9288KB
stdin
a
b
c
d
stdout
got 'a\nb\nc\nd\n' from stdin
got '' from stdin
got '0\n' from subprocess
got '1\n' from subprocess
got '2\n' from subprocess
got '3\n' from subprocess
got '4\n' from subprocess
got '' from subprocess