I'm using Python to call a C++ program using the subprocess module. Since the program takes some time to run, I'd like to be able to terminate it using Ctrl+C. I've seen a few questions regarding this on StackOverflow but none of the solutions seem to work for me.
What I would like is for the subprocess to be terminated on KeyboardInterrupt. This is the code that I have (similar to suggestions in other questions):
import subprocess
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()
However, if I run this, the code is hung up waiting for the process to end and never registers the KeyboardInterrupt. I have tried the following as well:
import subprocess
import time
binary_path = '/path/to/binary'
args = 'arguments' # arbitrary
call_str = '{} {}'.format(binary_path, args)
proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()
This code snippet works fine at terminating the program, so it's not the actual signal that's being sent to terminate that is the problem.
How can I change the code so that the subprocess can be terminated on KeyboardInterrupt?
I'm running Python 2.7 and Windows 7 64-bit. Thanks in advance!
Some related questions that I tried: