文件系统监控
-
文件系统监控是利用watchdog监控指定目录/文件的变化,如文件或目录的增删改查都会产生一个event事件信息,每种变化都会产生一个事件信息,且有一个特定的事件类与之对应。然后通过事件处理类来处理对应的事件。
-
watchdog需要从第三方库中下载
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} 文件夹 {event.src_path} 移动至 {event.dest_path}")
else:
print(f"{now} 文件由 {event.src_path} 移动至 {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} 创建文件夹 {event.src_path}")
else:
print(f"{now} 创建文件 {event.src_path}")
def on_deleted(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} 删除文件夹 {event.src_path}")
else:
print(f"{now} 删除文件 {event.src_path}")
def on_modified(self, event):
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if event.is_directory:
print(f"{now} 修改文件夹 {event.src_path}")
else:
print(f"{now} 修改文件 {event.src_path}")
if __name__ == '__main__':
# 实例化“观察者”对象
observer = Observer()
# 监控目录路径
path = r'E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维'
event_handler = FileEventHandler()
observer.schedule(event_handler, path, True) # True表示递归子目录
print(f'监控目录 {path}')
# 开启监控
observer.start()
# 阻塞,使程序有序执行
observer.join()
# 输出结果:
# 监控目录 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维
# 2021-05-12 23:40:58 创建文件 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维\123.txt
# 2021-05-12 23:41:16 删除文件 E:\PycharmProjects\untitled\project01\自动化运维\1.基础运维\123.txt