""" Running this file normally will do nothing but print 'start ' However, if you interrupt it once it's sleeping, it will expose a subtlety in the Popen code which can result in a parent process's stdout getting returned in the child process's stdout """ import signal import subprocess import sys import time sys.stdout.write('start ') def term(signum, sf): sys.stdout.write('term ') sys.stdout.flush() signal.signal(signal.SIGTERM, term) signal.signal(signal.SIGQUIT, term) signal.signal(signal.SIGINT, term) def snooze(): time.sleep(10) p = subprocess.Popen(['cat'], preexec_fn=snooze, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate('input') assert out == 'input', "doesn't match 'output': '%s'" % out