0%

利用watchdog监测文件系统

发现一个跨平台的对文件系统进行监测并由事件驱动进行操作的python工具——Watchdog,下面写一个简单的例子介绍如何使用watchdog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

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

class EventHandler(FileSystemEventHandler):

def on_created(self, event):
super(EventHandler, self).on_created(event)
self.file_name = event.src_path
if not event.is_directory:
print "create file: %s" % event.src_path
else:
print "create directory: %s" % event.src_path

def on_modified(self, event):
super(EventHandler, self).on_modified(event)
self.file_name = event.src_path
if not event.is_directory:
print "modify file: %s" % event.src_path
else:
print "modify directory: %s" % event.src_path


if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else './test/'
event_handler = EventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

其中EventHandler继承自FileSystemEventHandler,其中可以针对不同的文件操作类型编写不同的处理逻辑。