简体   繁体   English

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

[英]Python, cannot interrupt subprocess with Ctrl-C in windows

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. 我有一些Python代码可通过子进程调用外部可执行程序,并实时将输出读回GUI,我希望随时使用Ctrl-C中断外部二进制文件,但似乎不起作用。

I'm working on Windows. 我在Windows上工作。 I am hoping to stop the sub-process when hitting Ctrl-C. 我希望在按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()

Thanks to @JFSebastian, instead of using KeyboardInterrupt, I bind the keys (Ctrl+Delete) to my GUI, if the keys are down, the sub-process is terminated, and it works as following: 感谢@JFSebastian,而不是使用KeyboardInterrupt,而是将键(Ctrl + Delete)绑定到我的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()

I myself got into a similar situation sometime back where I was using a thread to run an executable and reading its data. 我自己有时也遇到类似情况,当时我使用线程来运行可执行文件并读取其数据。 I used the below approach to solve this problem 我用下面的方法解决了这个问题

import threading
import subprocess
import time

class binary_run():
    def __init__ (self):
        self.some_exe = "notepad.exe"

    def PrintOutputInRealTime(self):
        self.process = subprocess.Popen(self.some_exe,stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        while True:
            try:
                output = self.process.stdout.readline()
                if output == '' and self.process.poll() is not None:
                    break
                if output:
                    self.output_ctrl.write(output)
            except:
                pass

    def KillProcess(self):
        self.process.terminate()

if __name__ == "__main__":
    x = binary_run()
    worker = threading.Thread(target=x.PrintOutputInRealTime)
    worker.start()
    try:
        while worker.isAlive():
            time.sleep(0.5)
    except KeyboardInterrupt:
            print "Got Interrupt"
            x.KillProcess()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM