日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中文件变化监控-watchdog

發布時間:2023/12/20 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中文件变化监控-watchdog 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

起步

在python中文件監控主要有兩個庫,一個是pyinotify,一個是watchdog。pyinotify依賴于Linux平臺的inotify,后者則對不同平臺的的事件都進行了封裝。因為我主要用于Windows平臺,所以下面著重介紹watchdog(推薦大家閱讀一下watchdog實現源碼,有利于深刻的理解其中的原理)。
watchdog在不同的平臺使用不同的方法進行文件檢測。在init.py中發現了如下注釋:

|Inotify| Linux 2.6.13+ ``inotify(7)`` based observer |FSEvents| Mac OS X FSEvents based observer |Kqueue| Mac OS X and BSD with kqueue(2) ``kqueue(2)`` based observer |WinApi|(ReadDirectoryChangesW) MS Windows Windows API-based observer |Polling| Any fallback implementation

給出示例代碼如下:

#!/usr/bin/env python # -*- coding:utf-8 -*- # Created by victor# 本模塊的功能:<檢測文件夾變化># 導入watchdog對應模塊 from watchdog.observers import Observer from watchdog.events import * # 導入時間模塊 import timeclass FileEventHandler(FileSystemEventHandler):# 初始化魔術方法def __init__(self):FileSystemEventHandler.__init__(self)# 文件或文件夾移動def on_moved(self, event):if event.is_directory:print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))else:print("file moved from {0} to {1}".format(event.src_path,event.dest_path))# 創建文件或文件夾def on_created(self, event):if event.is_directory:print("directory created:{0}".format(event.src_path))else:print("file created:{0}".format(event.src_path))# 刪除文件或文件夾def on_deleted(self, event):if event.is_directory:print("directory deleted:{0}".format(event.src_path))else:print("file deleted:{0}".format(event.src_path))# 移動文件或文件夾def on_modified(self, event):if event.is_directory:print("directory modified:{0}".format(event.src_path))else:print("file modified:{0}".format(event.src_path))if __name__ == "__main__":# 實例化Observer對象observer = Observer()event_handler = FileEventHandler()# 設置監聽目錄dis_dir = "e:/"observer.schedule(event_handler,dis_dir,True)observer.start()try:while True:# 設置監聽頻率(間隔周期時間)time.sleep(1)except KeyboardInterrupt:observer.stop()observer.join()

小結

watchdog主要采用觀察者模型(廢話,從變量命名就可以看出來)。主要有三個角色:observer,event_handler,被監控的文件夾。三者原本是獨立的,主要通過observer.schedule函數將三者串起來,意思為observer不斷檢測調用平臺依賴代碼對監控文件夾進行變動檢測,當發現改變時,通知event_handler處理。最后特別推薦讀者有時間可以閱讀一下watchdog的源碼,寫的易懂而且架構很好用

總結

以上是生活随笔為你收集整理的python中文件变化监控-watchdog的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。