PHpullh
학습 라이브러리/Python/파일 감시 (watchdog)

PYTHON · 파일/IO

파일 감시 (watchdog)

파일 시스템 변경을 감지하여 자동 작업을 수행하는 패턴입니다.

파일/IO고급watchdog파일 감시filesystem이벤트

핵심 설명

파일 시스템 변경을 감지하여 자동 작업을 수행하는 패턴입니다.

Python code

import os
import time
from pathlib import Path

# 간단한 폴링 기반 파일 감시
class SimpleWatcher:
    def __init__(self, path: str):
        self.path = Path(path)
        self._snapshot: dict[str, float] = {}

    def take_snapshot(self) -> dict[str, float]:
        snapshot = {}
        if self.path.is_dir():
            for f in self.path.iterdir():
                if f.is_file():
                    snapshot[str(f)] = f.stat().st_mtime
        return snapshot

    def check_changes(self) -> dict:
        new_snapshot = self.take_snapshot()
        changes = {"created": [], "modified": [], "deleted": []}

        for path, mtime in new_snapshot.items():
            if path not in self._snapshot:
                changes["created"].append(path)
            elif mtime != self._snapshot[path]:
                changes["modified"].append(path)

        for path in self._snapshot:
            if path not in new_snapshot:
                changes["deleted"].append(path)

        self._snapshot = new_snapshot
        return changes

# watchdog 라이브러리 패턴
# from watchdog.observers import Observer
# from watchdog.events import FileSystemEventHandler
#
# class MyHandler(FileSystemEventHandler):
#     def on_modified(self, event):
#         print(f"변경: {event.src_path}")
#     def on_created(self, event):
#         print(f"생성: {event.src_path}")
#
# observer = Observer()
# observer.schedule(MyHandler(), path=".", recursive=True)
# observer.start()

watcher = SimpleWatcher("/tmp")
snapshot = watcher.take_snapshot()
print(f"감시 중: {len(snapshot)}개 파일")
print("파일 감시 시스템 준비 완료")

학습 팁

실제 프로젝트에서는 pip install watchdog을 사용하세요. OS 레벨 이벤트를 사용하여 폴링보다 효율적입니다.

주의할 점

폴링 기반 감시는 CPU를 소비합니다. 간격을 너무 짧게 설정하면 성능에 영향을 줍니다.

자주 묻는 질문

파일 감시 (watchdog)란 무엇인가요?

파일 시스템 변경을 감지하여 자동 작업을 수행하는 패턴입니다.

파일 감시 (watchdog) 학습 시 주의할 점은 무엇인가요?

폴링 기반 감시는 CPU를 소비합니다. 간격을 너무 짧게 설정하면 성능에 영향을 줍니다.