使用Python监控文件内容变化代码实例

yipeiwu_com4年前Python基础

利用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修改list中所有元素类型的三种方法

修改list中所有元素类型: 方法一: new = list() a = ['1', '2', '3'] for x in a: new.append(int(x)) print(...

Python实现定时精度可调节的定时器

本文实例为大家分享了Python实现定时精度可调节的定时器,供大家参考,具体内容如下 # -* coding: utf-8 -*- import sys import os...

如何用python写一个简单的词法分析器

如何用python写一个简单的词法分析器

编译原理老师要求写一个java的词法分析器,想了想决定用python写一个。 目标 能识别出变量,数字,运算符,界符和关键字,用excel表打印出来。 有了目标,想想要怎么实现词法分析器...

pytorch中的embedding词向量的使用方法

Embedding 词嵌入在 pytorch 中非常简单,只需要调用 torch.nn.Embedding(m, n) 就可以了,m 表示单词的总数目,n 表示词嵌入的维度,其实词嵌入就...

python 遍历pd.Series的index和value

遍历pd.Series的index和value的方法如下,python built-in list的enumerate方法不管用 for i, v in s.items(): p...