当前位置: 移动技术网 > IT编程>脚本编程>Python > 使用Python监控文件内容变化代码实例

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

2018年08月20日  | 移动技术网IT编程  | 我要评论

平新h,如何写日记,清穿之冷王的皇贵妃

利用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()

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网