• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论

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

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

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

#/usr/bin/env python#-*- coding=utf-8 -*- pos = 0while 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 osimport datetimeimport pyinotifyimport logging pos = 0def 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&quo<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i>t;,pyinotify.ALL_EVENTS,rec=True)  eh = MyEventHandler()  notifier = pyinotify.Notifier(wm,eh)  notifier.loop()if __name__ == "__main__":  main()

相关推荐:

如何使用Python的Requests包实现模拟登陆

以上就是使用Python监控文件内容变化代码的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用Python监控文件内容变化代码
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址