from __future__ import annotations import argparse import ctypes import locale import os import subprocess import sys from pathlib import Path from typing import TextIO def _set_console_title(title: str) -> None: if os.name == "nt": ctypes.windll.kernel32.SetConsoleTitleW(title) def _open_console_output(encoding: str) -> tuple[TextIO | None, bool]: if os.name == "nt": try: return open("CONOUT$", "w", encoding=encoding, errors="replace", buffering=1), True except OSError: pass return sys.stdout, False def _write_console(stream: TextIO | None, value: str) -> bool: if stream is None: return False try: stream.write(value) stream.flush() return True except (OSError, ValueError): return False def main() -> int: parser = argparse.ArgumentParser(description="Run a service in a visible console and tee its output to a log file.") parser.add_argument("--title", default="后台服务") parser.add_argument("--log", required=True) parser.add_argument("--pid-file", required=True) parser.add_argument("command", nargs=argparse.REMAINDER) args = parser.parse_args() command = list(args.command) if command and command[0] == "--": command.pop(0) if not command: parser.error("missing service command after --") _set_console_title(args.title) log_path = Path(args.log) pid_path = Path(args.pid_file) log_path.parent.mkdir(parents=True, exist_ok=True) pid_path.parent.mkdir(parents=True, exist_ok=True) encoding = locale.getpreferredencoding(False) or "utf-8" environment = os.environ.copy() executable = Path(command[0]) if executable.name.lower() in {"catalina.bat", "catalina.sh"} and executable.exists(): environment["CATALINA_HOME"] = str(executable.parent.parent) console_output, owns_console_output = _open_console_output(encoding) opened_console_output = console_output if owns_console_output else None process: subprocess.Popen[str] | None = None try: with log_path.open("a", encoding="utf-8") as log_file: process = subprocess.Popen( command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding=encoding, errors="replace", bufsize=1, shell=False, env=environment, ) pid_path.write_text(str(process.pid), encoding="ascii") assert process.stdout is not None for line in process.stdout: if not _write_console(console_output, line): console_output = None log_file.write(line) log_file.flush() return process.wait() except KeyboardInterrupt: if process is None: return 1 process.terminate() return process.wait() finally: if process is not None and process.stdout is not None: process.stdout.close() try: pid_path.unlink() except FileNotFoundError: pass if opened_console_output is not None: opened_console_output.close() if __name__ == "__main__": raise SystemExit(main())