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

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

我正在尝试对系统中的某些目录进行持续监控,因此我使用了 WatchDog API。我正在使用的功能:

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()

我感兴趣的事件仅在我覆盖 WatchDog 的另一个方法时被删除 class:

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

使用主函数:

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()

每当我使用 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

但是,如果我将主要功能代码更改为在单个路径上调用 watcher() 方法,则它可以正常工作:

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

完整代码可用Here

这是python中的坑之一:需要在pth后面加一个逗号:-)

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

您的代码传递了 20 个(resp 18)个字符作为参数,而不是一个字符串。