监控单个文件夹
from watchdog.events import *
from watchdog.observers import Observer
class ReceiveHandler(FileSystemEventHandler):
"""接收微信文件触发复制"""
# def on_created(self, event):
# FileManangement(event.src_path)
def on_moved(self, event):
FileManangement(event.dest_path)
# now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# print(now_str, 'Moved', os.path.split(event.dest_path)[-1])
# def on_deleted(self, event):
# now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# print(now_str, 'Delete', os.path.split(event.src_path)[-1])
def receive_monitor(watch_dir):
now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print("=" * 20, "【文件管理系统】", now_str, "=" * 20)
print('【受监控目录一】', watch_dir)
event_handler = ReceiveHandler()
observer = Observer()
observer.schedule(event_handler, path=watch_dir, recursive=True)
# 监控器启动——创建线程
observer.start()
# 以下代码是为了保持主线程运行
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
# 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程再终止
observer.join()
监控多个文件夹
def receive_monitor(watch_dirs: list):
now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print("=" * 20, "【文件管理系统】", now_str, "=" * 20)
event_handler = ReceiveHandler()
observer = Observer()
i = 0
for dir in watch_dirs:
i = i + 1
print('【受监控目录 %s】' % i, dir)
observer.schedule(event_handler, path=dir, recursive=True)
# 监控器启动——创建线程
observer.start()
# 以下代码是为了保持主线程运行
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
# 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程再终止
observer.join()