python监控文件内容是否变化_Python监控文件内容变化

#/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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值