实时监控第三方库watchdog,其原理通过操作系统的时间触发的,不需要循环和等待

使用场景:

  1.监控文件系统中文件或目录的增删改情况

  2.当特定的文件被创建,删除,修改,移动时执行相应的任务

1. 安装

pip install watchdog

示例:

1)监控文件内容变更触发响应操作

import re
import os
import logging
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') LUA_FILE_NAME = 'version_info.lua' #Lua版本文件
WHITELIST_FILE_NAME = 'whitelist.txt' # 白名单文件 class FileMonitorHandler(FileSystemEventHandler):
def __init__(self, **kwargs):
super(FileMonitorHandler, self).__init__(**kwargs)
# 监控目录 目录下面以device_id为目录存放各自的图片
self._watch_path = game_path # 重写文件改变函数,文件改变都会触发文件夹变化
def on_modified(self, event):
if not event.is_directory: # 文件改变都会触发文件夹变化
file_path = event.src_path
logging.info("file changed: %s " % file_path)
file_name = os.path.split(file_path)[-1]
# 白名单或者配置文件修改,则触发事件
if file_name == LUA_FILE_NAME: # lua文件发生变化
# 验证该目录下是否存在白名单文件
whitelist_file, is_exists = check_file_exists(file_path, WHITELIST_FILE_NAME)
if not is_exists: # 不存在白名单,则不进行修改操作
logging.info(f'{whitelist_file} not exists')
else:
# 读取文件进行替换操作
whitelist_handler(file_path, whitelist_file)
elif file_name == WHITELIST_FILE_NAME: # 白名单文件发生变化
# 验证配置文件是否存在
lua_file, is_exists = check_file_exists(file_path, LUA_FILE_NAME)
if not is_exists: # 不存在Lua文件
logging.info(f'{lua_file} not exists')
else:
whitelist_handler(lua_file, file_path)
else:
logging.info('Director changed') def on_created(self, event):
pass def check_file_exists(path, file_name):
"""
验证文件的存在性
"""
file_path = os.path.join(os.path.dirname(path), file_name)
is_exists = os.path.isfile(file_path)
return file_path, is_exists def replace_content(lua_file, new_str):
with open(lua_file, 'r', encoding='utf-8') as f1, open("%s.bak" % lua_file, "w", encoding='utf-8') as f2:
old_content = f1.read()
if 'testId' in old_content:
# 进行正则匹配
pattern = re.compile(r'testId = "(.*?)"', re.M | re.S)
new_content = re.sub(pattern, f'testId = "{new_str}"', old_content)
logging.info('Old content:%s' % old_content)
logging.info('New content:%s' % new_content)
f2.write(new_content) os.remove(lua_file)
os.rename("%s.bak" % lua_file, lua_file) def whitelist_handler(lua_file, whitelist_file):
"""
白名单处理
"""
with open(whitelist_file, 'r', encoding='utf-8') as f:
whitelist_content = f.read().replace("\n", "")
logging.info(f'Replace content: lua_file->{lua_file} whitelist content->{whitelist_content}')
replace_content(lua_file, whitelist_content) def main():
event_handler = FileMonitorHandler()
observer = Observer()
observer.schedule(event_handler, path=game_path, recursive=True) # recursive递归的
observer.start()
observer.join() if __name__ == '__main__':
global game_path
game_path = '/test2/files'
main()

2)项目文件变更触发Git提交(实时同步到代码仓库)

#!/usr/bin/python
# -*- coding: utf-8 -*- import sys
import time
import ntpath
import os
import re
import platform from subprocess import call
from shutil import copy
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler # git root path for files to push to remote
DIR_FOR_GIT = os.path.dirname(os.path.abspath(__file__)) # 执行需要监控的同步的文件
SYNC_FILE_LIST = [
'Redis.md',
'MySQL+Redis.md',
'MySQL.md',
] class FileChangeHandler(FileSystemEventHandler):
def on_modified(self, event):
# print('文件发生变化')
src_path = event.src_path.replace('\\', '/')
base_name = os.path.basename(src_path)
# print('base_name:', base_name)
if base_name in SYNC_FILE_LIST:
# print('src_path:', src_path)
os.chdir(DIR_FOR_GIT)
git_add_cmd = "git add -A"
git_commit_cmd = "git commit -m " + re.escape("Update " + base_name)
if platform.system() == "Windows":
git_commit_cmd = "git commit -m Update."
git_pull_cmd = "git pull origin main"
git_push_cmd = "git push origin main"
call(
git_add_cmd + "&&" +
git_commit_cmd + "&&" +
git_pull_cmd + "&&" +
git_push_cmd,
shell=True
) if __name__ == "__main__":
observer = Observer()
event_handler = FileChangeHandler() for file_path in SYNC_FILE_LIST:
file_path = os.path.join(DIR_FOR_GIT, file_path)
# print('当前文件路径', file_path)
observer.schedule(event_handler, path=os.path.dirname(os.path.realpath(file_path)), recursive=False) observer.start() try:
while True:
time.sleep(10)
except KeyboardInterrupt:
# print('服务中断')
observer.stop()
observer.join()

添加对应的监控程序之后, 可以在windows上开机自启动

@echo off
pythonw E:\www\项目\file_sync.py
:: echo "hello,bat"

然后将bat文件以快捷方式发送到桌面, 然后将其拖入启动项目录

C:\Users\用户名\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

  

常见问题:

  1. OSError: inotify watch limit reached 错误

在添加监控任务之后, 发现出现这个错误, 是因为已经达到了inotify监控的一个上限值

  查看目前的上限值:

cat /proc/sys/fs/inotify/max_user_watches
默认是8192

  解决:

1)临时生效
echo 81920 > /proc/sys/fs/inotify/max_user_watches 2)永久
在 /etc/sysctl.conf 中添加一行:
fs.inotify.max_user_watches=99999999
修改后保存
立即生效 sysctl -p

基于python的文件监控watchdog的更多相关文章

  1. 基于python openOPC的监控页面一

    笔者涉猎的工业领域项目遇到一个需求,需要把底层设备(表记)的状态和运行数据集中放到一个监控画面进行展示,数据需要在界面端实时进行刷新,类似网友的例子,如下图(侵删) 数据需要实时主动刷新,笔者基于多年 ...

  2. 基于python的文件处理

    二.文件操作方法大全 1.os.mknod("test.txt") 创建空文件2.fp = open("test.txt",w) 直接打开一个文件,如果文件不存 ...

  3. nomon+ pyNmonAnalyzer实现基于python的nmon监控性能数据可视化

    pip install pyNmonAnalyzer nnmon  for linux from sourceforge:https://sourceforge.net/projects/nmon/ ...

  4. python中文件变化监控-watchdog

    在python中文件监控主要有两个库,一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一个是watchdog(http://pytho ...

  5. python操作文件练习,配置haproxy

    在使用python操作文件的时候,特别是对于网络设备,通常操作配置文件,会简化配置量,配置文件加载到内存中,运行时使用的是内存中的配置,内存中配置修改后立即生效,如果不将配置内容保存到硬盘中,则下次重 ...

  6. 性能测试 基于Python结合InfluxDB及Grafana图表实时监控Android系统和应用进程

    基于Python结合InfluxDB及Grafana图表实时监控Android系统和应用进程   By: 授客 QQ:1033553122     1. 测试环境 2. 实现功能 3. 使用前提 4. ...

  7. Python 基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控

    基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控   By: 授客 QQ:1033553122   1.测试环境 python 3.4 zookeeper- ...

  8. Python基于Python实现批量上传文件或目录到不同的Linux服务器

    基于Python实现批量上传文件或目录到不同的Linux服务器   by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用方法 1 1. 编辑配置文件conf/rootpath_fo ...

  9. 基于Python——实现远程下载sftp文件(只下载.zip文件)

    [背景]远程下载发布包等文件时,总是要使用WinSCP等工具登陆拖动.今天就介绍一种使用python下载文件到本地的方法. [代码实现] import paramiko # paramiko模块,基于 ...

  10. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

随机推荐

  1. sql日期创建

    TRUNCATE TABLE SYS_DATEINFO declare @i int set @i=-30000 WHILE @i<1000000 BEGIN INSERT INTO SYS_D ...

  2. Python网页应用开发神器Dash 2.18.1稳定版本来啦

    本文示例代码已上传至我的Github仓库:https://github.com/CNFeffery/dash-master Gitee同步仓库地址:https://gitee.com/cnfeffer ...

  3. 2024.7.5-2024.7.20 HA省学会集训游记(焦作一中)

    这是一篇长篇小说 DAY1 除了DAY4-DAY5个别内容以外,这些都是补的,但是全写完有太多了qwq,挑题写了 树状数组和线段树基础 很多都是一些模板题,太模板的题不再做太多解释 题目: P4062 ...

  4. Java实现随机抽奖的方法有哪些

    在Java中实现随机抽奖的方法,通常我们会使用java.util.Random类来生成随机数,然后基于这些随机数来选择中奖者.以下将给出几种常见的随机抽奖实现方式,包括从数组中抽取.从列表中抽取以及基 ...

  5. ROS基础入门——实操教程

    ROS基础入门--实操教程 前言 本教程实操为主,少说书.可供参考的文档中详细的记录了ROS的实操和理论,只是过于详细繁杂了,看得脑壳疼,于是做了这个笔记. Ruby Rose,放在这里相当合理 前言 ...

  6. 2022年3月中国数据库排行榜:TiDB “三连降”仍霸榜首,“常胜四将军”得分集体下跌

    春暖花开好时光,三月一号迎榜来.2022年3月的 中国数据库流行度排行榜 已在墨天轮社区发布,本月共有 199个 数据库参与排名,相比上月新增四个数据库.排名前十的数据库得分均有所波动,整体排名变动略 ...

  7. 1. 什么是three.js?

    Three.js是一个基于JavaScript编写的开源3D图形库,它使用WebGL技术在网页上渲染3D图形.Three.js提供了许多高级功能,如几何体.纹理.光照.阴影等,以便开发者能够快速地创建 ...

  8. 2. 说一下vue2和vue3的区别 ?

    1. vue3 使用 proxy 替换Object.defineProperty 实现数据响应式 ,所以vue3 的性能得到了提升 : 2. vue3 使用组合式 API 替代了 vue2 中的选项式 ...

  9. KubeSphere Meetup 北京站火热报名中 | 搭载 CIC 2021 云计算峰会

    "CIC 2021 云计算峰会"是一场 Top 级行业盛会,将汇聚 800 家青云QingCloud 企业客户信息化负责人,采取线上线下相结合的方式,与会规模将超过 10000 人 ...

  10. 云原生周刊:Kubernetes 1.27 服务器端字段校验和 OpenAPI V3 进阶至 GA

    开源项目推荐 KubeView KubeView 是一个 Kubernetes 集群可视化工具和可视化资源管理器.它允许用户在集群内部运行命令,并查看集群内部的资源使用情况.容器运行状态.网络流量等. ...