Python_条件触发之—文件以及目录改变触发

自动触发

文件监控

 方案: 
    方案一:定时任务 + File_lastModified

 python中文件监控主要有两个库,
   一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),pyinotify依赖于Linux平台的inotify,
   一个是watchdog(http://pythonhosted.org/watchdog/),对不同平台的的事件都进行了封装.
 01.指定一个文件或目录作为watchdog observer的参数对象,
       它会不断监视该文件夹的任何更改,如文件的创建、修改、删除或文件从一个文件夹移动到另一个文件夹。
 02.当观察者记录或观察到事件时,事件处理程序会执行指定的事件操作。
    观察者模型主要有三个角色:
      observer、event_handler、被监控的文件夹。,
    三者原本是独立的 主要通过observer.schedule函数将三者串起来,
    意思为observer 不断检测调用平台依赖代码对监控文件夹进行变动检测,当发现改变时,通知event_handler处理

实现中提出的概念

0.event.src_path:
	指定的被监控的目录
 
1. Event
 01.Event-class
     watchdog.events.FileSystemEvent()  
	 watchdog.events.FileCreatedEvent FileModifiedEvent FileMovedEvent FileDeletedEvent FileOpendEvent  FileclosedEvent
	 watchdog.events.DirCreatedEvent()  DirModifiedEvent DirMovedEvent DirDeletedEvent
 02.Event-handler-class -重写对应实例方法
   	 from watchdog.events import LoggingEventHandler
     from watchdog.events import FileSystemEventHandler
	 from watchdog.events import PatternMatchingEventHandler
	 from watchdog.events import RegexMatchingEventHandler
  event.event_type:事件类型,例如 moved,deleted,created,modified
2.observer 
  observer.schedule(event_handler, path, recursive=False) 
  observer.add_handler_for_watch(event_handler, watch):添加1个新的事件处理器到	

应用场景

以编写一个脚本来自动归类下载后的文件
 watchdog 模块为我们提供了 DirectorySnapshot 功能-快照功能	

linux命令行

  watch 命令是Linux系统中一个非常有用的命令,
     它可以周期性地执行指定的命令,并将命令的输出结果实时显示在终端上
	 ##  #为了突出变化部分,可以使用 -d(difference)参数  高亮变化内容
     watch -n 1  -d cat hello.txt	
  timeout 命令  Ctrl+C。如果需要自动退出,可以结合使用timeout命令	

  管道 xargs		  

代码

# -*- coding:utf-8 -*-
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import argparse

class MyEventHandler(FileSystemEventHandler):
    """ 创建自定义类,继承基类,重写相应实例方法"""
    ## 方法处理文被创建事件
    def __init__(self) -> None:
        super().__init__()

    def on_created(self, event):
        path = event.src_path
        file_name = os.path.basename(path)
        if file_name.endswith("json") or file_name.endswith("txt") or file_name.endswith("py"):
            print(file_name,"文件格式正确")
        else:
            pass
        print(event)

class Watcher:
    def __init__(self):
        self.handler_dict =dict()      
        self.observer= Observer()
    
    def add_handler(self,event_handler: FileSystemEventHandler, path: str):
        self.handler_dict[event_handler] = path

    def run(self):
        if self.handler_dict is not None:
            for event_handler, path in self.handler_dict.items():
        # 声明一个定时任务, recursive 表示是否递归子目录,即监听子目录,默认为 False
                self.observer.schedule(event_handler, path, recursive=True)
            # 声明一个定时任务
            self.observer.start()
            try:
                while True:
                    # 每隔一秒
                    time.sleep(1)
            finally:
                self.observer.stop()
            # 等待监控器 线程结束
            self.observer.join()    

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='arg parser')
    parser.add_argument('--root', type=str,
                        default=r"/data/228",
                        help="motive dir ")
    args = parser.parse_args()
    my_src_path = args.root

    my_event_handler = MyEventHandler()
    w = Watcher() 
    w.add_handler(my_event_handler,my_src_path)
    w.run()

    ## nohup python /data/watch/trigger_check.py  >output.log 2>&1 &

参考

 python文件监控模块Watchdog使你的文件管理更轻松 https://www.jianshu.com/p/db75b99f9d47 
 python watchdog 示例  https://blog.51cto.com/u_16175466/7041456
posted @ 2024-02-26 18:09  辰令  阅读(17)  评论(0编辑  收藏  举报