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


本文摘自php中文网,作者不言,侵删。

这篇文章主要介绍了关于使用Python监控文件内容变化代码,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

在python中文件监控主要有两个库,一个是pyinotify,一个是watchdog。pyinotify依赖于Linux平台的inotify,今天我们就来探讨下pyinotify.

利用seek监控文件内容,并打印出变化内容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#/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监控文件内容变化,当文件逐渐变大时,可轻松完成任务:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

#!/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监控文件内容变化代码的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

如何用Python客户端开发?用实例进行Python模块详解

基于tpc-c基准的Python orm的性能测试详解

Python的缩进规则是什么

Python 为什么不支持 switch 语句?

Python中*的用法介绍(代码示例)

Python如何另起一行

Python egg怎么安装

水仙花数如何用Python代码表示?

Python是什么?Python如何使用?

Python中insert用法是什么

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...