python监控文件变化
網(wǎng)址: https://blog.csdn.net/qq_40223983/article/details/102889329
起步
在python中文件監(jiān)控主要有兩個(gè)庫,一個(gè)是pyinotify,一個(gè)是watchdog。pyinotify依賴于Linux平臺的inotify,后者則對不同平臺的的事件都進(jìn)行了封裝。因?yàn)槲抑饕糜赪indows平臺,所以下面著重介紹watchdog(推薦大家閱讀一下watchdog實(shí)現(xiàn)源碼,有利于深刻的理解其中的原理)。
watchdog在不同的平臺使用不同的方法進(jìn)行文件檢測。在init.py中發(fā)現(xiàn)了如下注釋:
|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
# 本模塊的功能:<檢測文件夾變化>
# 導(dǎo)入watchdog對應(yīng)模塊
from watchdog.observers import Observer
from watchdog.events import *
# 導(dǎo)入時(shí)間模塊
import time
class FileEventHandler(FileSystemEventHandler):
# 初始化魔術(shù)方法
def __init__(self):
FileSystemEventHandler.__init__(self)
# 文件或文件夾移動(dòng)
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))
# 創(chuàng)建文件或文件夾
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))
# 移動(dòng)文件或文件夾
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__":
# 實(shí)例化Observer對象
observer = Observer()
event_handler = FileEventHandler()
# 設(shè)置監(jiān)聽目錄
dis_dir = "e:/"
observer.schedule(event_handler,dis_dir,True)
observer.start()
try:
while True:
# 設(shè)置監(jiān)聽頻率(間隔周期時(shí)間)
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
小結(jié)
watchdog主要采用觀察者模型(廢話,從變量命名就可以看出來)。主要有三個(gè)角色:observer,event_handler,被監(jiān)控的文件夾。三者原本是獨(dú)立的,主要通過observer.schedule函數(shù)將三者串起來,意思為observer不斷檢測調(diào)用平臺依賴代碼對監(jiān)控文件夾進(jìn)行變動(dòng)檢測,當(dāng)發(fā)現(xiàn)改變時(shí),通知event_handler處理。最后特別推薦讀者有時(shí)間可以閱讀一下watchdog的源碼,寫的易懂而且架構(gòu)很好用
總結(jié)
以上是生活随笔為你收集整理的python监控文件变化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序配置文件记录
- 下一篇: 食品甲醛检测仪有哪些实用的功能