gpt4 book ai didi

python - 目录监控中的看门狗不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:37 24 4
gpt4 key购买 nike

我想监视文件夹中文件的添加、修改和删除,并在发生任何此类事件时执行命令。

我发现这个教程有帮助 https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory所以这是我现在的代码

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



class Watcher:
DIRECTORY_TO_WATCH = "/Users/***/desktop/google drive/protpics"


def __init__(self):
self.observer = Observer()


def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
self.observer.start()
try:

while True:
time.sleep(5)

except:
self.observer.stop()
print("Error")

self.observer.join()


class Handler(FileSystemEventHandler):

@staticmethod
def on_my_event(event):
if event.is_directory:
return None

elif event.event_type == 'created':
#Take any action here when a file is first created.
print ("Recived created event - %s" % event.src_path)

elif event.event_type == 'modified':
# Take any action here when a file is modified.
print ("Recieved modified event - %s" % event.src_path)


if __name__ == '__main__':
W = Watcher()
W.run()

现在的问题是,当我向目录添加新文件时,没有消息打印出来。我做错了什么以及如何解决它?

最佳答案

您无法弄清楚您的代码和示例之间的区别吗?在您的链接中,作者使用 on_any_event,但您使用的是 on_my_event。没有名为 on_my_event 的方法。

查看官方文档:http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEventHandler

关于python - 目录监控中的看门狗不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48332855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com