【问题标题】:Killing all processes and threads in python3.X杀死python3.X中的所有进程和线程
【发布时间】:2020-07-13 09:44:20
【问题描述】:

我正在编写一个 UI 包装器,用于使用 esptool.py 读取一些信息

我有两个活动线程:UI 和处理 - SerialReader。 UI 类引用了 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) 无济于事。 我已经研究过这个问题,但找不到解决方案。

操作系统是 Ubuntu,我不关心跨平台功能,但它们会很好

【问题讨论】:

标签: python-3.x multithreading ubuntu kill


【解决方案1】:

首先导入操作系统库:

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)) 

【讨论】:

  • 嗨,它不起作用(来自 pycharm)。 stvofl 的评论来自 pycharm。另外,它不会杀死所有正在运行的python3程序吗?
  • 是的,它会杀死所有 python3 程序。我已经在我的应用程序中使用了这段代码,因为我使用了多处理并希望在退出时消除所有进程。
【解决方案2】:

如cmets中所说,将线程设置为守护进程解决了问题:

super().__init__(daemon=True)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多