使用Python监控文件内容变化代码实例
程序员文章站
2022-10-11 16:23:26
利用seek监控文件内容,并打印出变化内容:
#/usr/bin/env python
#-*- coding=utf-8 -*-
pos = 0
w...
利用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实现的个人所得税计算器示例
下一篇: 最晚的牙