使用Python监控文件内容变化代码实例
作者:guoswcfl 时间:2021-06-05 22:45:19
利用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()
来源:http://blog.51cto.com/guoshiwei/2124306
标签:Python,监控文件内容
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python绘制已知点的坐标的直线实例
2023-03-12 08:36:11
Python开发之QT解决无边框界面拖动卡屏问题(附带源码)
2023-10-31 09:31:29
![](https://img.aspxhome.com/file/2023/6/66816_0s.png)
Oracle SQL中实现indexOf和lastIndexOf功能的思路及代码
2023-07-14 10:26:52
Golang中panic的异常处理
2023-10-13 12:27:23
Mysql中explain的使用详解
2009-12-08 16:18:00
ajax实现Dig程序中的投票
2008-01-22 17:27:00
![](https://img.aspxhome.com/file/UploadPic/20081/22/2008122173320740s.jpg)
JavaScript解释型模版
2009-10-19 23:12:00
php打印输出棋盘的实现方法
2023-10-09 04:38:10
python数据分析之单因素分析线性拟合及地理编码
2021-02-09 06:46:20
![](https://img.aspxhome.com/file/2023/6/65516_0s.png)
WEB2.0网页制作标准教程(3)定义语言编码
2007-11-13 13:23:00
python PyTorch参数初始化和Finetune
2023-04-26 08:53:44
![](https://img.aspxhome.com/file/2023/4/75934_0s.png)
眼未动,心已动【碳酸饮料会】
2009-09-01 19:32:00
![](https://img.aspxhome.com/file/UploadPic/20099/1/t1qlbxxobrxxxxxxxx-455-221-73s.jpg)
JS实现淡入淡出图片效果的方法分析
2023-08-24 08:45:44
python实现简单的五子棋游戏
2023-07-30 13:24:31
从零学python系列之从文件读取和保存数据
2021-02-11 01:51:29
详解如何利用Python绘制科赫曲线
2023-05-02 15:26:42
![](https://img.aspxhome.com/file/2023/1/78491_0s.png)
python爬取淘宝商品销量信息
2023-06-01 14:59:03
Django使用消息提示简单的弹出个对话框实例
2023-02-08 06:23:07
![](https://img.aspxhome.com/file/2023/1/66911_0s.jpg)
解决Windows10不能安装Oracle 11g的问题(附详细安装教程)
2023-07-23 08:22:08
![](https://img.aspxhome.com/file/2023/3/63723_0s.jpg)
关于php unset对json_encode的影响详解
2023-07-06 08:33:52
![](https://img.aspxhome.com/file/2023/6/55356_0s.png)