杀死 python3.X 中的所有进程和线程

Killing all processes and threads in python3.X

我正在编写一个 UI 包装器,用于使用 esptool.py

读取一些信息

我有两个活动线程:UI 和处理 - SerialReader。 UI class 引用了 SerialReader,当它收到退出命令时应该停止 SerialReader。

问题是我调用了 esptool 命令,它在尝试通过串行连接读取数据时卡住了。

class SerialReaderProcess(threading.Thread):

    def __init__(self, window):
        super().__init__()
        self.window = window
        self.logger = window.logger
        self.window.set_thread(self)
        self._stop_event = threading.Event()

    def run(self):
        ...
        #read chip id
        esptool.main(['chip_id'])
        ...

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

我想要的是杀死这个程序的所有活动进程。当我关闭 UI 并调用 serialReaderProcess.stop() 时,它不会停止进程。我可以在控制台上看到 esptool 的输出。

我不在乎我是否中断任何事情,没有数据会被破坏。

我试过 sys.exit(0) 没用。 我已经研究了这个问题,但找不到解决方案。

OS 是 Ubuntu,我不关心跨平台功能,但它们会很好

首先导入os库:

Import os

然后你可以在你的exit_event方法中写下下面的代码:

def closeEvent(self, event):  
    output,errors = p1.communicate() 
    bashCommand = "killall python3"
    sudoPassword = 'your password' 
    p = os.system('echo %s|sudo -S %s' % (sudoPassword, bashCommand)) 

如评论所述,将线程设置为守护进程解决了问题:

super().__init__(daemon=True)

守护线程在程序退出时自动终止。

关于守护进程的更多信息: Daemon Threads Explanation