Search code examples
pythonpython-3.xpython-watchdog

How do I fix TypeError: dispatch() missing 1 required positional argument: 'event'


I was trying to create a script that automatically sorts files. Of course, I need to be able to move files to get this whole thing working but I can't even do that.

I am always getting the same error Message which does not seem to come from my Code if I am getting it right. I attached my code and would be very grateful if you could help me. I know I am not supposed to post a whole file but I actually have no clue where this error comes from.

This is my Code:

import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
import json

event = None

class MyHandler(FileSystemEventHandler):
    i = 1
    def on_modified(self, event):
        for filename in os.listdir(folder_to_track):
            src = folder_to_track + "/" + filename
            new_destination = folder_destination + "/" + filename
            os.rename(src, new_destination)

folder_to_track = '/Users/Balduin/Pictures/Florens1019'
folder_destination = '/Users/Balduin/Pictures/Florens1019/raw-jpeg'
event_handler = MyHandler
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive=True)
observer.start()

try:
    while True:
        time.sleep(10)
except KeyboardInterrupt:
    observer.stop()
observer.join

This is the Error I am getting:

Exception in thread Thread-6:
Traceback (most recent call last):
  File "C:\Users\Balduin\Anaconda3\lib\threading.py", line 917, in 
_bootstrap_inner
    self.run()
  File "C:\Users\Balduin\Anaconda3\lib\site- 
packages\watchdog\observers\api.py", line 199, in run
    self.dispatch_events(self.event_queue, self.timeout)
  File "C:\Users\Balduin\Anaconda3\lib\site- 
packages\watchdog\observers\api.py", line 368, in dispatch_events
    handler.dispatch(event)
TypeError: dispatch() missing 1 required positional argument: 'event'

Solution

  • Try

    event_handler = MyHandler()
    

    instead of

    event_handler = MyHandler
    

    dispatch() function which is defined in watchdog's api.py file (\Anaconda3\lib\site-packages\watchdog\observers\api.py) expects an argument (event):

    handler.dispatch(event)
    

    however, you haven't instantiated your event_handler and therefore no argument is passed when calling handler.dispath().