Home > Software engineering >  TypeError: <Function> takes X positional argument but X were given
TypeError: <Function> takes X positional argument but X were given

Time:12-17

I'm trying to do a continuous monitor of some directories in the system so I used WatchDog API. The function I'm using:

def watcher(HRSpath):
    src_path = HRSpath
    event_handler = Handler()
    observer = watchdog.observers.Observer()
    observer.schedule(event_handler, path=src_path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

The events I'm interested in is delete only as I'm overriding another method from WatchDog class:

class Handler(watchdog.events.PatternMatchingEventHandler):
    def on_deleted(self, event):
        print("Watchdog received deleted event - % s." % event.src_path)

Using the main function:

if __name__ == '__main__':
    pth = "/home/abd/Downloads/"
    pth2 = "/home/abd/Desktop/"

    Proc1 = multiprocessing.Process(target=watcher, args=(pth))
    Proc2 = multiprocessing.Process(target=watcher, args=(pth2))
    Proc1.start()
    Proc2.start()

The code always yields an error saying whenever I use Multiprocessing/Threading class:

Process Process-1: Traceback (most recent call last): File "/usr/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) TypeError: watcher() takes 1 positional argument but 20 were given Process Process-2: Traceback (most recent call last): File "/usr/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/lib/python3.9/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) TypeError: watcher() takes 1 positional argument but 18 were given

Process finished with exit code 0

However, if I changed the main function code to call on watcher() method on a single path it works with no issue:

 if __name__ == '__main__':
        pth = "/home/abd/Downloads/"
        watcher(pth)

The full code is available Here

CodePudding user response:

This is one of the pitfalls in python: you need to add a comma after pth :-)

Proc1 = multiprocessing.Process(target=watcher, args=(pth, ))

Your code passes 20 (resp 18) characters as arguments, and not one string.

  • Related