[python] 파일 발견 시 알림 설정하기

최근에 파일 시스템에서 특정 파일이 생성되거나 삭제될 때 알림을 받고 싶은 경우가 있습니다. Python의 Watchdog 라이브러리를 사용하면 파일 시스템 감시 및 이벤트 처리를 간편하게 할 수 있습니다.

Watchdog 라이브러리 설치

먼저 Watchdog 라이브러리를 설치해야 합니다. 아래의 명령을 사용하여 pip를 통해 간단히 설치할 수 있습니다.

pip install watchdog

감시자 설정

Watchdog를 사용하기 위해서는 Observer 및 EventHandler를 설정해야 합니다. 아래는 새로운 파일 생성 시 알림을 받는 예제 코드입니다.

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class NewFileHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            print(f"새로운 파일이 생성되었습니다: {event.src_path}")

if __name__ == "__main__":
    path = "."  # 감시할 디렉토리 경로
    event_handler = NewFileHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

위 코드는 현재 디렉토리를 감시하며, 새로운 파일이 생성될 때마다 해당 파일의 경로를 출력합니다.

종합적인 옵션

on_created 외에도 on_modified, on_deleted 등 여러 파일 시스템 이벤트에 대한 핸들러를 정의할 수 있습니다. 또한, 감시할 디렉토리의 경로나 감시 대상 파일의 확장자 등 다양한 설정을 통해 보다 다양한 시나리오에 사용할 수 있습니다.

Watchdog 라이브러리를 사용하면 파일 시스템의 변화를 실시간으로 감지하고 효과적으로 처리할 수 있습니다.

더 많은 정보는 Watchdog 공식 문서를 참고하시기 바랍니다.