1

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

Invader Zim
  • 796
  • 2
  • 14
  • 39
  • 1
    Change to `super().__init__(daemon=True)`, read about [Daemon Threads Explanation](https://stackoverflow.com/a/190017/7414759) – stovfl Jul 13 '20 at 12:13

2 Answers2

0

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)) 
  • 1
    Hi, it didn't work (from pycharm). And the comment from stvofl worked from pycharm. Also, woudln't it kill all python3 programs that are running? – Invader Zim Jul 13 '20 at 12:52
  • Yes, it kills all python3 programs. I have already used this code in my application because I used multiprocessing and wanted to eliminate all processes when exiting. – Ali Rohanizadeh Jul 13 '20 at 13:07
0

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

Invader Zim
  • 796
  • 2
  • 14
  • 39