基于Python Watchdog庫實(shí)現(xiàn)文件系統(tǒng)監(jiān)控
Watchdog是一個(gè)優(yōu)秀的Python庫,用于監(jiān)控文件系統(tǒng)事件。它可以檢測(cè)文件或目錄的創(chuàng)建、修改、刪除和移動(dòng)等操作,并觸發(fā)相應(yīng)的回調(diào)函數(shù)。本文將介紹Watchdog的基本用法,并通過一個(gè)實(shí)際案例展示如何用它來監(jiān)控下載目錄并自動(dòng)轉(zhuǎn)換ICO文件為PNG格式。
Watchdog簡介
Watchdog庫的主要組件包括:
- Observer - 監(jiān)控文件系統(tǒng)變化的核心類
- FileSystemEventHandler - 處理文件系統(tǒng)事件的基類
- 各種事件類 - 如FileCreatedEvent, FileModifiedEvent等
安裝Watchdog
pip install watchdog
實(shí)際案例:自動(dòng)轉(zhuǎn)換ICO文件為PNG
下面是一個(gè)完整的示例,它監(jiān)控用戶的下載目錄,當(dāng)檢測(cè)到新的ICO文件時(shí),自動(dòng)將其轉(zhuǎn)換為PNG格式(使用ImageMagick的convert工具)。
import os import time import subprocess import shutil from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class ICOHandler(FileSystemEventHandler): def __init__(self, download_dir, convert_exe): self.download_dir = download_dir self.processed_files = set() self.convert_exe = convert_exe # 初始化時(shí)處理已存在的ico文件 for filename in os.listdir(download_dir): if filename.lower().endswith('.ico'): self.processed_files.add(filename) self.convert_ico_to_png(filename) def on_created(self, event): if not event.is_directory and event.src_path.lower().endswith('.ico'): filename = os.path.basename(event.src_path) if filename not in self.processed_files: self.processed_files.add(filename) print(f"檢測(cè)到新的ICO文件: {filename}") self.convert_ico_to_png(filename) def convert_ico_to_png(self, ico_filename): ico_path = os.path.join(self.download_dir, ico_filename) base_name = os.path.splitext(ico_filename)[0] # 臨時(shí)輸出目錄 temp_dir = os.path.join(self.download_dir, f"{base_name}_temp") os.makedirs(temp_dir, exist_ok=True) # 臨時(shí)輸出路徑模板 temp_output = os.path.join(temp_dir, f"{base_name}_%d.png") try: # 使用ImageMagick的convert命令轉(zhuǎn)換ICO到PNG cmd = [ self.convert_exe, ico_path, temp_output ] subprocess.run(cmd, check=True) print(f"已轉(zhuǎn)換: {ico_filename} -> 多個(gè)PNG文件") # 找出最大的PNG文件 largest_file = self.find_largest_png(temp_dir) if largest_file: final_output = os.path.join(self.download_dir, f"{base_name}.png") os.rename(largest_file, final_output) print(f"已保存最大的PNG文件: {final_output}") # 清理臨時(shí)目錄 self.cleanup_temp_dir(temp_dir) except subprocess.CalledProcessError as e: print(f"轉(zhuǎn)換失敗: {e}") self.cleanup_temp_dir(temp_dir) except Exception as e: print(f"發(fā)生錯(cuò)誤: {e}") self.cleanup_temp_dir(temp_dir) def find_largest_png(self, directory): largest_size = 0 largest_file = None for filename in os.listdir(directory): if filename.lower().endswith('.png'): filepath = os.path.join(directory, filename) file_size = os.path.getsize(filepath) if file_size > largest_size: largest_size = file_size largest_file = filepath return largest_file def cleanup_temp_dir(self, temp_dir): try: for filename in os.listdir(temp_dir): filepath = os.path.join(temp_dir, filename) os.remove(filepath) os.rmdir(temp_dir) except Exception as e: print(f"清理臨時(shí)目錄時(shí)出錯(cuò): {e}") def main(): # 獲取用戶下載目錄 download_dir = os.path.expanduser('~/Downloads') # 在這里設(shè)置ImageMagick的convert.exe的完整路徑 # 如果'convert'在您的系統(tǒng)PATH中,您可以直接寫'convert' # 否則,請(qǐng)?zhí)峁┩暾窂?,例? r'C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\convert.exe' convert_exe = 'convert' # 查找并打印convert命令的完整路徑 # 如果用戶沒有提供絕對(duì)路徑,則在PATH中搜索 if convert_exe == 'convert' and not os.path.isabs(convert_exe): full_path = shutil.which(convert_exe) if full_path: print(f"查找到 'convert' 的完整路徑是: {full_path}") convert_exe = full_path # 使用完整路徑以提高可靠性 else: print(f"警告: 在系統(tǒng)PATH中找不到 '{convert_exe}'。程序可能會(huì)失敗。") # 確保ImageMagick已安裝 try: subprocess.run([convert_exe, '--version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except (subprocess.CalledProcessError, FileNotFoundError): print(f"錯(cuò)誤: 無法執(zhí)行 '{convert_exe}'。") print("請(qǐng)檢查路徑是否正確,或ImageMagick是否已安裝并添加到系統(tǒng)PATH中。") print("您可以修改腳本中 'convert_exe' 變量的值為 convert.exe 的完整路徑。") print("ImageMagick下載地址: https://imagemagick.org/script/download.php") return print(f"開始監(jiān)控目錄: {download_dir}") print("按Ctrl+C停止監(jiān)控") event_handler = ICOHandler(download_dir, convert_exe) observer = Observer() observer.schedule(event_handler, download_dir, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": main()
代碼解析
1.ICOHandler類 - 繼承自FileSystemEventHandler,處理文件系統(tǒng)事件
on_created
: 當(dāng)新文件創(chuàng)建時(shí)觸發(fā)convert_ico_to_png
: 轉(zhuǎn)換ICO文件為PNG格式find_largest_png
: 找出最大的PNG文件(ICO可能包含多個(gè)尺寸)cleanup_temp_dir
: 清理臨時(shí)目錄
2.Observer設(shè)置 - 創(chuàng)建觀察者并設(shè)置監(jiān)控目錄
3.ImageMagick檢查 - 確保轉(zhuǎn)換工具可用
使用場(chǎng)景
這個(gè)腳本特別適合需要批量處理ICO圖標(biāo)的場(chǎng)景,例如:
- 網(wǎng)頁開發(fā)者需要將ICO轉(zhuǎn)換為PNG用于網(wǎng)站
- UI設(shè)計(jì)師需要提取ICO中的最大尺寸圖標(biāo)
- 系統(tǒng)管理員需要自動(dòng)化處理下載的圖標(biāo)文件
擴(kuò)展思路
Watchdog的強(qiáng)大之處在于它可以應(yīng)用于各種文件系統(tǒng)監(jiān)控場(chǎng)景,例如:
- 自動(dòng)備份新創(chuàng)建的文件
- 監(jiān)控日志文件變化并發(fā)送通知
- 自動(dòng)解壓下載的壓縮文件
- 照片自動(dòng)分類整理
總結(jié)
Watchdog是一個(gè)功能強(qiáng)大且易于使用的Python庫,可以輕松實(shí)現(xiàn)文件系統(tǒng)監(jiān)控功能。通過本文的案例,我們展示了如何用它來監(jiān)控特定目錄并自動(dòng)處理新文件。你可以根據(jù)自己的需求修改這個(gè)示例,實(shí)現(xiàn)更復(fù)雜的文件處理邏輯。
要運(yùn)行這個(gè)腳本,你需要先安裝ImageMagick并將其添加到系統(tǒng)PATH中,或者修改腳本中的convert_exe
變量為ImageMagick convert工具的完整路徑。
以上就是基于Python Watchdog庫實(shí)現(xiàn)文件系統(tǒng)監(jiān)控的詳細(xì)內(nèi)容,更多關(guān)于Python Watchdog系統(tǒng)監(jiān)控的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python新手學(xué)習(xí)可變和不可變對(duì)象
在本篇文章里小編給大家分享了是一篇關(guān)于python可變對(duì)象和不可變對(duì)象的基礎(chǔ)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以參考下。2020-06-06python多進(jìn)程實(shí)現(xiàn)進(jìn)程間通信實(shí)例
這篇文章主要介紹了python多進(jìn)程實(shí)現(xiàn)進(jìn)程間通信實(shí)例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11Python使用低通濾波器模糊圖像功能實(shí)現(xiàn)
這篇文章主要介紹了Python使用低通濾波器模糊圖像,我們介紹了多種不同類型的濾波器核與卷積操作,使用 scipy.ndimage 模塊中的濾波器模糊圖像,利用 scipy.fftpack 模塊的 fft2() 函數(shù)實(shí)現(xiàn)高斯模糊,介紹了scipy.signal模塊的彩色圖像頻域卷積,需要的朋友可以參考下2023-03-03python 統(tǒng)計(jì)list中各個(gè)元素出現(xiàn)的次數(shù)的幾種方法
這篇文章主要介紹了python 統(tǒng)計(jì)list中各個(gè)元素出現(xiàn)的次數(shù)的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02解決python升級(jí)引起的pip執(zhí)行錯(cuò)誤的問題
今天小編就為大家分享一篇解決python升級(jí)引起的pip執(zhí)行錯(cuò)誤的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06Python?Pandas讀取Excel日期數(shù)據(jù)的異常處理方法
Excel文件是傳統(tǒng)的數(shù)據(jù)格式,但面對(duì)海量數(shù)據(jù)時(shí),用編程的方法來處理數(shù)據(jù)更有優(yōu)勢(shì),下面這篇文章主要給大家介紹了關(guān)于Python?Pandas讀取Excel日期數(shù)據(jù)的異常處理方法,需要的朋友可以參考下2022-02-02