Python使用watchdog监控文件系统
- wtachdog不是python内置的模块,需要pip安装
- 这里使用的python3.9
监控了D盘 /test目录及其子目录下面的操作。
代码如下
from watchdog.observers import Observer
from watchdog.events import *
import time
class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
def on_moved(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} Directory was moved from {event.src_path} to {event.dest_path}")
else:
print(f"{now} File was moved from {event.src_path} to {event.dest_path}")
def on_created(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} Directory {event.src_path} was created")
else:
print(f"{now} File {event.src_path} was created")
def on_deleted(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} Directory {event.src_path} was deleted")
else:
print(f"{now} File {event.src_path} was deleted")
def on_modified(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} Directory {event.src_path} was modified")
else:
print(f"{now} File {event.src_path} was modified")
if __name__ == "__main__":
observer = Observer()
path = "d:\\test"
event_handler = FileEventHandler()
observer.schedule(event_handler, path, True)
print(f"Start monitor directory {path}")
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join
对d:\test目录下进行一些操作:控制台显示结果如下