import subprocess import threading import os import time stdin, stdout = os.pipe() def thread1(): p1 = subprocess.Popen("cmd /c echo Hello World!", stdout=stdout) p1.wait() print("[pipe.py] p1 is done") os.close(stdout) t1 = threading.Thread(target=thread1) t1.start() # To verify that the inheritable handles are leaking into the second # subprocess, uncomment this sleep. With the sleep, the inheritable handles # created by the other thread are already closed by the time that p2 starts. # #time.sleep(1) p2 = subprocess.Popen("cmd /c python reader.py", stdin=stdin) while True: try: p2.wait(1) except subprocess.TimeoutExpired: pass except KeyboardInterrupt: print("[pipe.py] Ctrl+C: Killing p2") p2.kill() p2.wait() else: print("[pipe.py] p2 is done") break print("[pipe.py] Done") ''' # reader.py import sys try: for line in sys.stdin: print("[reader.py] Line:", line.rstrip()) except KeyboardInterrupt: print("[reader.py] Ctrl+C") except EOFError: print("[reader.py] Ctrl+D") print("[reader.py] Exiting") '''