This article mainly introduces the code for using Python to monitor file content changes. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
There are two main types of file monitoring in python. There are two libraries, one is pyinotify and the other is watchdog. pyinotify relies on inotify on the Linux platform. Today we will discuss pyinotify.
Use seek to monitor file content and print out the changed content:
#/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()
Use the tool pyinotify to monitor file content changes. When the file gradually becomes larger, you can easily complete the task:
#!/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()
Related recommendations:
How to use Python's Requests package implements simulated login
The above is the detailed content of Use Python to monitor file content changes code. For more information, please follow other related articles on the PHP Chinese website!