【发布时间】:2016-06-23 09:48:12
【问题描述】:
我有一些Python代码可以用子进程调用外部可执行程序,并将输出实时读回GUI,我希望随时用Ctrl-C中断外部二进制文件,但似乎不起作用。
我在 Windows 上工作。我希望在按下 Ctrl-C 时停止子进程。
这是我的代码:
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()
【问题讨论】:
标签: python subprocess copy-paste interrupt