import time import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import threading import pos_update_bill import pos_update_daily_product DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data')) FILE_EXTENSIONS = ('.xls', '.xlsx') BILL_PREFIX = "영수증별매출상세현황" DAILY_PRODUCT_PREFIX = "일자별 (상품별)" class NewFileHandler(FileSystemEventHandler): def __init__(self): super().__init__() self._lock = threading.Lock() self._processing_files = set() def on_created(self, event): if event.is_directory: return filepath = event.src_path filename = os.path.basename(filepath) if not filename.endswith(FILE_EXTENSIONS): return # 처리 대상 여부 확인 if filename.startswith(BILL_PREFIX) or filename.startswith(DAILY_PRODUCT_PREFIX): print(f"[WATCHER] 신규 파일 감지: {filename}") threading.Thread(target=self.process_file, args=(filepath, filename), daemon=True).start() def process_file(self, filepath, filename): with self._lock: if filename in self._processing_files: print(f"[WATCHER] {filename} 이미 처리 중") return self._processing_files.add(filename) try: time.sleep(3) # 파일 쓰기 완료 대기 print(f"[WATCHER] 파일 처리 시작: {filename}") if filename.startswith(BILL_PREFIX): pos_update_bill.main() elif filename.startswith(DAILY_PRODUCT_PREFIX): pos_update_daily_product.main() else: print(f"[WATCHER] 처리 대상이 아님: {filename}") return except Exception as e: print(f"[WATCHER] 처리 중 오류 발생: {filename} / {e}") else: try: os.remove(filepath) print(f"[WATCHER] 파일 처리 완료 및 삭제: {filename}") except Exception as e: print(f"[WATCHER] 파일 삭제 실패: {filename} / {e}") finally: with self._lock: self._processing_files.discard(filename) def start_watching(): print(f"[WATCHER] '{DATA_DIR}' 폴더 감시 시작") event_handler = NewFileHandler() observer = Observer() observer.schedule(event_handler, DATA_DIR, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: print("[WATCHER] 감시 종료 요청 수신, 종료 중...") observer.stop() observer.join() if __name__ == "__main__": start_watching()