I was hoping to depend on atexit to stop a thread which would otherwise be blocking.
I found that the registered method will not be called when I call sys.exit() while the thread is running.
I found the function is called if the thread is not running.
import os
import atexit
import threading
import sys
class Watcher:
def __init__(self, to_watch, callback):
self.path_to_watch = to_watch
self.stop_flag = False
self._monitor_thread = threading.Thread(target=self.monitor_thread)
self._monitor_thread.start()
atexit.register(self.stop)
def stop(self):
print(f'stopping watcher on {self.path_to_watch}')
self.stop_flag=True
def monitor_thread(self):
while not self.stop_flag:
pass
if __name__ == '__main__':
def my_callback( file, action):
print(file, action)
dw = Watcher('.', my_callback)
sys.exit(0)
Is this expected behavior? I don't see any documentation of this in atexit.
Is there a better way to catch that the main thread is terminating and stop my threads?