Killing all processes and threads in python3.X

柔情痞子 提交于 2021-02-10 14:50:20

问题


I'm writing a UI wrapper for reading some info using esptool.py

I have two active threads: UI and procesing - SerialReader. UI class has reference to the SerialReader and should stop SerialReader when it gets the exit command.

The problem is that I call esptool command which gets stuck in trying to read data over serial connection.

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

What I want is to kill all active process of this program. When I call close the UI and call serialReaderProcess.stop() it doesn't stop the process. I can see the output of esptool on the console.

I don't care if I interrupt anything, no data can be corrupted.

I've tried sys.exit(0) to no avail. I've researched the problem but couldn't find a solution.

The OS is Ubuntu and I don't care about cross-platform features, but they would be nice


回答1:


First import os library:

Import os

Then you can write the following code in your exit_event method:

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



回答2:


As stated in comments, setting the thread as Daemon solved the problem:

super().__init__(daemon=True)

Daemon threads are automatically killed when the program quits.

More about daemons: Daemon Threads Explanation



来源:https://stackoverflow.com/questions/62873234/killing-all-processes-and-threads-in-python3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!