监控单个文件夹

  1. from watchdog.events import *
  2. from watchdog.observers import Observer
  3. class ReceiveHandler(FileSystemEventHandler):
  4. """接收微信文件触发复制"""
  5. # def on_created(self, event):
  6. # FileManangement(event.src_path)
  7. def on_moved(self, event):
  8. FileManangement(event.dest_path)
  9. # now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  10. # print(now_str, 'Moved', os.path.split(event.dest_path)[-1])
  11. # def on_deleted(self, event):
  12. # now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  13. # print(now_str, 'Delete', os.path.split(event.src_path)[-1])
  14. def receive_monitor(watch_dir):
  15. now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  16. print("=" * 20, "【文件管理系统】", now_str, "=" * 20)
  17. print('【受监控目录一】', watch_dir)
  18. event_handler = ReceiveHandler()
  19. observer = Observer()
  20. observer.schedule(event_handler, path=watch_dir, recursive=True)
  21. # 监控器启动——创建线程
  22. observer.start()
  23. # 以下代码是为了保持主线程运行
  24. try:
  25. while True:
  26. time.sleep(1)
  27. except KeyboardInterrupt:
  28. observer.stop()
  29. # 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程再终止
  30. observer.join()

监控多个文件夹

  1. def receive_monitor(watch_dirs: list):
  2. now_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  3. print("=" * 20, "【文件管理系统】", now_str, "=" * 20)
  4. event_handler = ReceiveHandler()
  5. observer = Observer()
  6. i = 0
  7. for dir in watch_dirs:
  8. i = i + 1
  9. print('【受监控目录 %s】' % i, dir)
  10. observer.schedule(event_handler, path=dir, recursive=True)
  11. # 监控器启动——创建线程
  12. observer.start()
  13. # 以下代码是为了保持主线程运行
  14. try:
  15. while True:
  16. time.sleep(1)
  17. except KeyboardInterrupt:
  18. observer.stop()
  19. # 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程再终止
  20. observer.join()