python wathchdog 实现监控本地文件增,删,改,移

# -*- coding:utf-8 -*-
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import settings as config
import time
import os
import json
# token = f"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIgIjoiYWNjZXNzIiwiZXhwIjoxNjY5NzI2NzY3LCJpYXQiOjE2Njk2ODM1NjcsImp0aSI6ImY4YzZhNDRiMDExOTRhMTk5YzdkZjcwMDNhNTM3Yzc4IiwicGVyc29uX2lkIjo1LCJuYW1lIjoiYWRtaW4ifQ.KNMTuRslHzMsT4rB3vTY-pixE7EKRGbeIZm9L9OExSE"

'''

监控某个文件夹内部 子文件 以及 子目录  重命名/移动/删除/新增

'''

# 监控文件
WATCH_PATTERNS = "*"  # 监控文件的模式
IGNORE_PATTERNS = ""  # 设置忽略的文件模式
IGNORE_DIRECTORIES = False  # 是否忽略文件夹变化
CASE_SENSITIVE = True  # 是否对大小写敏感
GO_RECURSIVELY = True  # 是否监控子文件夹

class Monitor():
    # 所做 事件列表
    result = []
    # 重命名文件夹列表
    on_move_dirs = []
    # 重命名文件列表
    on_move_files = []

    # 添加
    def on_created(self,event):
        Monitor.result.append((config.ACTIONS.get("CREATED"), event.src_path))

    #删除
    def on_deleted(self,event):
        Monitor.result.append((config.ACTIONS.get("DELETED"),event.src_path))

    #修改
    def on_modified(self,event):
        if os.path.isfile(event.src_path):
            Monitor.result.append((config.ACTIONS.get("UPDATED"), event.src_path))

    #重命名
    def on_moved(self,event):
        if os.path.isdir(event.dest_path):
            Monitor.on_move_dirs.append({"src_path":event.src_path,"current_path":event.dest_path})
        else:
            Monitor.on_move_files.append({"src_path":event.src_path,"current_path":event.dest_path})

    #生成 event_handler 对象
    def create_event_handler(self,watch_path):
        event_handler = PatternMatchingEventHandler(WATCH_PATTERNS, IGNORE_PATTERNS,
                                                    IGNORE_DIRECTORIES, CASE_SENSITIVE)

        event_handler.on_created = self.on_created
        event_handler.on_deleted = self.on_deleted
        event_handler.on_modified = self.on_modified
        event_handler.on_moved = self.on_moved

        watch_path = watch_path  # 监控目录
        my_observer = Observer()
        my_observer.schedule(event_handler, watch_path, recursive=GO_RECURSIVELY)
        my_observer.start()
        return my_observer

    def main(self,watch_path):
        my_observer = self.create_event_handler(watch_path)
        try:
            remove_dict = {}
            add_list = []
            tag = 0
            remove_path = []
            remove_tag = 0
            time_tag = 0
            while True:
                if time.time()>time_tag:
                    time_tag = time.time()
                # 此处 重命名 文件夹/文件 简单处理,不排除出现问题情况 后期加校验
                if Monitor.on_move_dirs:
                    print(Monitor.on_move_dirs[-1], "重命名")

                if Monitor.on_move_files:
                    if not Monitor.on_move_dirs:
                        print(Monitor.on_move_files[-1], "重命名")
                Monitor.on_move_files=[]
                Monitor.on_move_dirs = []
                if Monitor.result:
                    time.sleep(0.2)
                    tag_s = False
                    # 去重
                    result = list(set(Monitor.result))
                    #排序 根据 ACTIONS
                    result = sorted(
                            result,
                            key=lambda t: t[0],
                            reverse=True
                    )
                    print("-------------------------------------------------------")
                    # print(result, "result        ")
                    print("-------------------------------------------------------")
                    result_tag = []
                    for action, full_filename in result:
                        if action != config.ACTIONS.get("DELETED"):
                            # 不全为删除 tag_s 标记
                            tag_s = True
                        result_tag.append(action)
                    for action, full_filename in result:
                        if action == config.ACTIONS.get("DELETED") and tag_s:
                            remove_dict[full_filename] = None
                            tag += 1
                        elif action == config.ACTIONS.get("CREATED"):
                            if tag >= 1:
                                # 如果 remove_dict 已有key
                                try:
                                    for key, value in remove_dict.items():
                                        key_ward = os.path.split(key)
                                        value_ward = os.path.split(full_filename)
                                        if value is None and key_ward[-1] == value_ward[-1]:
                                            if key_ward[0] != value_ward[0]:
                                                remove_dict[key] = full_filename
                                                # 记录移动 path
                                                remove_path.append(full_filename)
                                            else:
                                                del remove_dict[key]
                                            tag -= 1
                                except:
                                    pass
                                if tag == 0:
                                    time_tag += 4
                                    for src_path, dest_path in remove_dict.items():
                                        print({src_path:dest_path}, "移动")
                                    remove_dict = {}
                                remove_tag += 1
                            else:
                                if time_tag <= time.time():
                                    remove_path = []
                                    remove_tag = 0
                                if remove_path:
                                    # 存在移动 path
                                    if remove_tag:
                                        full_filename_index = os.path.split(full_filename)[0]
                                        path_tag = False
                                        for path in remove_path:
                                            if path in full_filename_index:
                                                # 当前路径不存在 移动路径中
                                                path_tag = True
                                        if not path_tag:
                                            print(full_filename, "新增")
                                else:
                                    print(full_filename, "新增")
                        elif action == config.ACTIONS.get("UPDATED"):
                            # 更新
                            if not os.path.isdir(full_filename):
                                if full_filename not in add_list:
                                    if (config.ACTIONS.get("CREATED"),full_filename) not in result:
                                        print(full_filename, "修改")
                        if not tag_s:
                            print(full_filename, "删除")
                            tag = 0
                    Monitor.result = []
                    add_list = []
                time.sleep(1)

        except KeyboardInterrupt:
            my_observer.stop()
            my_observer.join()

if __name__ == "__main__":
    path_dir = r"D:\Desktop\pr"
    try:
        Monitor().main(watch_path=path_dir)
    except Exception as e:
        print(e,"ssssssssss")

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值