ホームページ  >  記事  >  バックエンド開発  >  Python を使用してファイル内容の変更コードを監視する

Python を使用してファイル内容の変更コードを監視する

不言
不言オリジナル
2018-06-04 11:59:103457ブラウズ

この記事では、主に Python を使用してファイルの内容の変更を監視するためのコードを紹介します。これには、必要な友人が参照できるように共有します。は pyinotify 、1 つはウォッチドッグです。 pyinotify は、Linux プラットフォームの inotify に依存しています。今日は、pyinotify について説明します。

ファイルの内容を監視し、変更を出力するには、

#/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 の Requests パッケージを使用してシミュレートされたログインを実装する方法


以上がPython を使用してファイル内容の変更コードを監視するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。