基于Python Watchdog庫實現(xiàn)文件系統(tǒng)監(jiān)控
Watchdog是一個優(yōu)秀的Python庫,用于監(jiān)控文件系統(tǒng)事件。它可以檢測文件或目錄的創(chuàng)建、修改、刪除和移動等操作,并觸發(fā)相應的回調(diào)函數(shù)。本文將介紹Watchdog的基本用法,并通過一個實際案例展示如何用它來監(jiān)控下載目錄并自動轉換ICO文件為PNG格式。
Watchdog簡介
Watchdog庫的主要組件包括:
- Observer - 監(jiān)控文件系統(tǒng)變化的核心類
- FileSystemEventHandler - 處理文件系統(tǒng)事件的基類
- 各種事件類 - 如FileCreatedEvent, FileModifiedEvent等
安裝Watchdog
pip install watchdog
實際案例:自動轉換ICO文件為PNG
下面是一個完整的示例,它監(jiān)控用戶的下載目錄,當檢測到新的ICO文件時,自動將其轉換為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
# 初始化時處理已存在的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"檢測到新的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]
# 臨時輸出目錄
temp_dir = os.path.join(self.download_dir, f"{base_name}_temp")
os.makedirs(temp_dir, exist_ok=True)
# 臨時輸出路徑模板
temp_output = os.path.join(temp_dir, f"{base_name}_%d.png")
try:
# 使用ImageMagick的convert命令轉換ICO到PNG
cmd = [
self.convert_exe,
ico_path,
temp_output
]
subprocess.run(cmd, check=True)
print(f"已轉換: {ico_filename} -> 多個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}")
# 清理臨時目錄
self.cleanup_temp_dir(temp_dir)
except subprocess.CalledProcessError as e:
print(f"轉換失敗: {e}")
self.cleanup_temp_dir(temp_dir)
except Exception as e:
print(f"發(fā)生錯誤: {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"清理臨時目錄時出錯: {e}")
def main():
# 獲取用戶下載目錄
download_dir = os.path.expanduser('~/Downloads')
# 在這里設置ImageMagick的convert.exe的完整路徑
# 如果'convert'在您的系統(tǒng)PATH中,您可以直接寫'convert'
# 否則,請?zhí)峁┩暾窂?,例? r'C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\convert.exe'
convert_exe = 'convert'
# 查找并打印convert命令的完整路徑
# 如果用戶沒有提供絕對路徑,則在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}'。程序可能會失敗。")
# 確保ImageMagick已安裝
try:
subprocess.run([convert_exe, '--version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except (subprocess.CalledProcessError, FileNotFoundError):
print(f"錯誤: 無法執(zhí)行 '{convert_exe}'。")
print("請檢查路徑是否正確,或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: 當新文件創(chuàng)建時觸發(fā)convert_ico_to_png: 轉換ICO文件為PNG格式find_largest_png: 找出最大的PNG文件(ICO可能包含多個尺寸)cleanup_temp_dir: 清理臨時目錄
2.Observer設置 - 創(chuàng)建觀察者并設置監(jiān)控目錄
3.ImageMagick檢查 - 確保轉換工具可用
使用場景
這個腳本特別適合需要批量處理ICO圖標的場景,例如:
- 網(wǎng)頁開發(fā)者需要將ICO轉換為PNG用于網(wǎng)站
- UI設計師需要提取ICO中的最大尺寸圖標
- 系統(tǒng)管理員需要自動化處理下載的圖標文件
擴展思路
Watchdog的強大之處在于它可以應用于各種文件系統(tǒng)監(jiān)控場景,例如:
- 自動備份新創(chuàng)建的文件
- 監(jiān)控日志文件變化并發(fā)送通知
- 自動解壓下載的壓縮文件
- 照片自動分類整理
總結
Watchdog是一個功能強大且易于使用的Python庫,可以輕松實現(xiàn)文件系統(tǒng)監(jiān)控功能。通過本文的案例,我們展示了如何用它來監(jiān)控特定目錄并自動處理新文件。你可以根據(jù)自己的需求修改這個示例,實現(xiàn)更復雜的文件處理邏輯。
要運行這個腳本,你需要先安裝ImageMagick并將其添加到系統(tǒng)PATH中,或者修改腳本中的convert_exe變量為ImageMagick convert工具的完整路徑。
以上就是基于Python Watchdog庫實現(xiàn)文件系統(tǒng)監(jiān)控的詳細內(nèi)容,更多關于Python Watchdog系統(tǒng)監(jiān)控的資料請關注腳本之家其它相關文章!
相關文章
python 統(tǒng)計list中各個元素出現(xiàn)的次數(shù)的幾種方法
這篇文章主要介紹了python 統(tǒng)計list中各個元素出現(xiàn)的次數(shù)的幾種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02
Python?Pandas讀取Excel日期數(shù)據(jù)的異常處理方法
Excel文件是傳統(tǒng)的數(shù)據(jù)格式,但面對海量數(shù)據(jù)時,用編程的方法來處理數(shù)據(jù)更有優(yōu)勢,下面這篇文章主要給大家介紹了關于Python?Pandas讀取Excel日期數(shù)據(jù)的異常處理方法,需要的朋友可以參考下2022-02-02

