"""One trading engine per data directory, even with different HTTP ports.""" from __future__ import annotations import os from pathlib import Path class RuntimeLock: def __init__(self, path: Path): self.path = Path(path) self.stream = None def __enter__(self): self.path.parent.mkdir(parents=True, exist_ok=True) stream = self.path.open("a+b") if stream.seek(0, os.SEEK_END) == 0: stream.write(b"\0") stream.flush() stream.seek(0) try: if os.name == "nt": import msvcrt msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: stream.close() raise RuntimeError("Движок уже запущен для этой папки. Откройте существующее окно программы.") from None self.stream = stream return self def __exit__(self, *args): if self.stream is not None: try: self.stream.seek(0) if os.name == "nt": import msvcrt msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1) else: import fcntl fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN) finally: self.stream.close() self.stream = None