目录监控中的看门狗不工作
watchdog in directory monitoring is not working
我想监视文件夹的文件添加、修改和删除,并在发生任何此类事件时执行命令。
我发现这个教程对我有帮助 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()
现在的问题是,当我将新文件添加到目录时,没有打印出任何消息。我做错了什么,我该如何解决?
你不能找出你的代码和示例代码之间的区别吗?在你的link中,作者使用on_any_event
,而你使用的是on_my_event
。没有名为 on_my_event
.
的方法
查看官方文档:http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEventHandler
我想监视文件夹的文件添加、修改和删除,并在发生任何此类事件时执行命令。
我发现这个教程对我有帮助 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()
现在的问题是,当我将新文件添加到目录时,没有打印出任何消息。我做错了什么,我该如何解决?
你不能找出你的代码和示例代码之间的区别吗?在你的link中,作者使用on_any_event
,而你使用的是on_my_event
。没有名为 on_my_event
.
查看官方文档:http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEventHandler