gpt4 book ai didi

Python,无法在 Windows 中使用 Ctrl-C 中断子进程

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:29 28 4
gpt4 key购买 nike

我有一些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()

最佳答案

感谢@J.F.Sebastian,我没有使用KeyboardInterrupt,而是将键(Ctrl+Delete)绑定(bind)到我的GUI,如果按下键,子进程将终止,其工作原理如下:

class binary_run():
def __init__ (self, tcl_file_name, cmd_str, output_ctrl, exe_cwd):

self.some_exe = "E:\\some.exe"
self.cmd = self.some_exe + cmd_str
self.output_ctrl = output_ctrl

self.output_ctrl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

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
self.process = subprocess.Popen(self.cmd, startupinfo=startupinfo, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

while True:
try:
#output = process.stdout.readline()
output = self.process.stdout.readline()
if output == '' and self.process.poll() is not None:
break
if output:
self.output_ctrl.write(output)
except KeyboardInterrupt:
self.process.terminate()

self.process.terminate()

def OnKeyDown(self, event):
controlDown = event.ControlDown()
keycode = event.GetKeyCode()

if (controlDown and keycode == wx.WXK_DELETE):
wx.MessageBox('Binary got interrupted!', 'INFO', wx.OK | wx.ICON_INFORMATION)
self.process.terminate()

def run_binary(self):
worker = Thread(target=self.PrintOutputInRealTime)
worker.start()

关于Python,无法在 Windows 中使用 Ctrl-C 中断子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35884487/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com