国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中文件變化監控示例(watchdog)

2020-01-04 16:35:44
字體:
來源:轉載
供稿:網友

在python/199254.html">python中文件監控主要有兩個庫,一個是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),一個是watchdog(http://pythonhosted.org/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

給出示例代碼如下:

from watchdog.observers import Observerfrom 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()event_handler = FileEventHandler()observer.schedule(event_handler,"d:/dcm",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的源碼,寫的易懂而且架構很好。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 普格县| 扎囊县| 区。| 明星| 汝州市| 广安市| 中江县| 苏尼特左旗| 洛宁县| 盐边县| 永平县| 平陆县| 曲阜市| 博湖县| 乌拉特前旗| 塔城市| 韶山市| 星子县| 方正县| 闵行区| 遵义县| 唐海县| 彝良县| 宿迁市| 班戈县| 安岳县| 天津市| 镶黄旗| 兴山县| 韶关市| 米易县| 洛南县| 铁力市| 金堂县| 平阴县| 麻阳| 哈尔滨市| 泸溪县| 揭阳市| 师宗县| 左贡县|