我想看一个文件夹来添加,修改和删除文件,并在发生任何此类事件时执行命令。
我发现本教程帮助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()
现在的问题是,当我向目录添加新文件时,没有消息被打印出来。我做错了什么,我该如何解决?
答案 0 :(得分:1)
难道你不能弄清楚你的代码和例子之间的区别吗?在您的链接中,作者使用on_any_event
,但您使用的是on_my_event
。没有名为on_my_event
的方法。
查看官方文件:http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEventHandler