Search code examples
pythonwatchdog

Python, Watchdog and Self Reference


I wanted to get run some Watchdog code. So here the example:

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from watchdog.events import FileSystemEventHandler

class FileDispatcherTask (FileSystemEventHandler):
  def __init__ (self, src, dest, queue):
    self._src = src
    self._dest = dest
    self._queue = queue;

  def dispatch (self, file):
    info = JobInfo(file)
    self._queue.addJob(info)

  def on_created (self, event):
    print ("File was created")
    print (event)

  async def run (self):
    observer = Observer()
    observer.schedule(self, self._src, recursive=False)
    observer.start()
    try:
      while True:
        time.sleep(1)
    finally:
      observer.stop()
      observer.join()

The code should run as a task where the observer is setup in the run method. The schedule method seems not to work with self because there are no outputs about creating files. Would I write a separate class for event listening, it works as expected. What am I missing? Isn't the self keyword like the this keyword in Java?


Solution

  • OK, I write normally in static typed languages my code, so I did the mistake that I accidentally overwrote the dispatch method of FileSystemEventHandler dispatch(event). Changing the name of method, everything works fine.