I wish to launch a rather long-running subprocess in Python, and would like to be able to terminate it with ^C
. However, pressing ^C
leads to the parent receiving KeyboardInterrupt
and terminating (and sometimes leaves sleep
as a defunct process).
import subprocess
subprocess.call("sleep 100".split())
How do I have it such that pressing ^C
only terminates the sleep
process (as we'd have on a shell command line), and allow the parent to continue? I believe I tried some combinations of using preexec_fn
, start_new_session
and shell
flags to call
, but with no success.
Edit: I know I can wrap the subprocess
invocation in a try-catch
block, and ignore the keyboard interrupt; but I don't want to do that. My question is this: the keyboard interrupt should have killed the sleep
, and should have been the end of it. Why is then propagated, as it were, to the parent. Or is it like the sleep
process was never the one to receive the interrupt? If not, how would I make it the foreground process?
Again, I'm trying to emulate the parent-child relationship of a command line. If I were to do the equivalent on a command line, I can get away without needing extra handling.