I have some Python code to call external executable program with sub-process, and read back the output to GUI in real-time, I hope to interrupt the external binary with Ctrl-C at anytime, but it seems not working.
I'm working on Windows. I am hoping to stop the sub-process when hitting Ctrl-C.
Here is my code:
class binary_run():
def __init__ (self, tcl_file_name, cmd_str, output_ctrl, exe_cwd):
self.some_exe = "E:\\some.exe"
self.cmd = cmd = self.some_exe + cmd_str
self.output_ctrl = output_ctrl
def PrintOutputInRealTime(self):
#The following two lines are to make sure the console window is hidden
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#Start the subprocess
process = subprocess.Popen(self.cmd, startupinfo=startupinfo, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while True:
try:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
self.output_ctrl.write(output)
except KeyboardInterrupt: #Never comes here
process.terminate()
process.terminate()
def run_binary(self):
worker = Thread(target=self.PrintOutputInRealTime)
worker.start()