发布时间:2019-09-08 09:10:08编辑:auto阅读(1754)
利用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---骰子游戏
下一篇: Python基本数据类型(三)
51271
50712
41315
38128
32589
29497
28350
23212
23183
21506
1581°
2303°
1911°
1852°
2172°
1894°
2584°
4322°
4174°
2979°