Handling OSError from Watchdog

前端 未结 1 361
星月不相逢
星月不相逢 2021-01-21 07:26

I have been using tkinter combined watchdog module to handle some uploading requests. Most of the time it works fine, but sometimes our network drive goes unstable and disconnec

相关标签:
1条回答
  • 2021-01-21 07:52

    This is how i solved this problem:

        from watchdog import observers
        from watchdog.observers.api import DEFAULT_OBSERVER_TIMEOUT, BaseObserver
    
    
        class MyEmitter(observers.read_directory_changes.WindowsApiEmitter):
            def queue_events(self, timeout):
                try:
                    super().queue_events(timeout)
                except OSError as e:
                    print(e)
                    connected = False
                    while not connected:
                        try:
                            self.on_thread_start()  # need to re-set the directory handle.
                            connected = True
                            print('reconnected')
                        except OSError:
                            print('attempting to reconnect...')
                            time.sleep(10)
    
    
        observer = BaseObserver(emitter_class=MyEmitter, timeout=DEFAULT_OBSERVER_TIMEOUT)
        ...
    

    Subclassing WindowsApiEmitter to catch the exception in queue_events. In order to continue after reconnecting, watchdog needs to re-set the directory handle, which we can do with self.on_thread_start().

    Then use MyEmitter with BaseObserver, we can now handle losing and regaining connection to shared drives.

    0 讨论(0)
提交回复
热议问题