使用Python监控文件内容变化代码实例
利用seek监控文件内容,并打印出变化内容:
#/usr/bin/envpython
#-*-coding=utf-8-*-
pos=0
whileTrue:
con=open("a.txt")
ifpos!=0:
con.seek(pos,0)
whileTrue:
line=con.readline()
ifline.strip():
printline.strip()
pos=pos+len(line)
ifnotline.strip():
break
con.close()
利用工具pyinotify监控文件内容变化,当文件逐渐变大时,可轻松完成任务:
#!/usr/bin/envpython
#-*-coding=utf-8-*-
importos
importdatetime
importpyinotify
importlogging
pos=0
defprintlog():
globalpos
try:
fd=open("log/a.txt")
ifpos!=0:
fd.seek(pos,0)
whileTrue:
line=fd.readline()
ifline.strip():
printline.strip()
pos=pos+len(line)
ifnotline.strip():
break
fd.close()
exceptException,e:
printstr(e)
classMyEventHandler(pyinotify.ProcessEvent):
defprocess_IN_MODIFY(self,event):
try:
printlog()
exceptException,e:
printstr(e)
defmain():
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()
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短