import os import sys import tempfile from pathlib import Path class SingleInstance: def __init__(self, app_name="PCM_Report"): self.lockfile = Path(tempfile.gettempdir()) / f"{app_name}.lock" self.fp = None def __enter__(self): try: if self.lockfile.exists(): # 尝试读取PID,检查进程是否还在运行 try: pid = int(self.lockfile.read_text().strip()) # 检查进程是否存在 if sys.platform == "win32": import ctypes kernel32 = ctypes.windll.kernel32 PROCESS_QUERY_INFORMATION = 0x0400 handle = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, 0, pid) if handle: kernel32.CloseHandle(handle) return False # 进程存在,不允许启动 else: os.kill(pid, 0) # Unix系统检查 return False except (ValueError, ProcessLookupError, OSError): # 进程不存在,删除旧锁文件 self.lockfile.unlink(missing_ok=True) # 创建锁文件 self.lockfile.write_text(str(os.getpid())) return True except Exception: return False def __exit__(self, *args): try: if self.lockfile.exists(): self.lockfile.unlink() except Exception: pass