网站首页 > 技术文章 正文
这篇文章主要介绍了关于使用Python监控文件内容变化代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
在python中文件监控主要有两个库,一个是pyinotify,一个是watchdog。pyinotify依赖于Linux平台的inotify,今天我们就来探讨下pyinotify.
利用seek监控文件内容,并打印出变化内容:
#/usr/bin/env python
#-*- coding=utf-8 -*-
pos = 0
while True:
con = open("a.txt")
if pos != 0:
con.seek(pos,0)
while True:
line = con.readline()
if line.strip():
print line.strip()
pos = pos + len(line)
if not line.strip():
break
con.close()
利用工具pyinotify监控文件内容变化,当文件逐渐变大时,可轻松完成任务:
#!/usr/bin/env python
#-*- coding=utf-8 -*-
import os
import datetime
import pyinotify
import logging
pos = 0
def printlog():
global pos
try:
fd = open("log/a.txt")
if pos != 0:
fd.seek(pos,0)
while True:
line = fd.readline()
if line.strip():
print line.strip()
pos = pos + len(line)
if not line.strip():
break
fd.close()
except Exception,e:
print str(e)
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_MODIFY(self,event):
try:
printlog()
except Exception,e:
print str(e)
def main():
printlog()
wm = pyinotify.WatchManager()
wm.add_watch("log/a.txt",pyinotify.ALL_EVENTS,rec=True)
eh = MyEventHandler()
notifier = pyinotify.Notifier(wm,eh)
notifier.loop()
if __name__ == "__main__":
main()
相关推荐:
如何使用Python的Requests包实现模拟登陆
以上就是使用Python监控文件内容变化代码的详细内容,更多请关注其它相关文章!
更多技巧请《转发 + 关注》哦!
- 上一篇: 118.Python——PyQt窗体上显示监控视频画面
- 下一篇: Python版智能监控应用实践
猜你喜欢
- 2024-12-18 118.Python——PyQt窗体上显示监控视频画面
- 2024-12-18 Python 全栈开发 -- 监控篇 python监控程序
- 2024-12-18 使用Python实现自动化网络安全监控与防护
- 2024-12-18 Python调用Prometheus监控数据并计算
- 2024-12-18 使用Python实现智能电网监控与优化系统
- 2024-12-18 Python脚本监控管理nginx python写监控脚本
- 2024-12-18 实时监控文件系统:探索Python Watchdog库的神奇之处!
- 2024-12-18 使用Python实现智能农业设备控制与监控
- 2024-12-18 Watchfiles vs Watchgod:Python 文件监控库的真实体验对比?
- 2024-12-18 如何用Python脚本来监控服务器(一)——自动化监控之Agent方式
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)