Files
AutoDeploy/deploy_tool/service_console.py

115 lines
3.6 KiB
Python
Raw Normal View History

2026-07-14 16:30:36 +08:00
from __future__ import annotations
import argparse
import ctypes
import locale
import os
import subprocess
import sys
from pathlib import Path
2026-10-09 09:12:14 +08:00
from typing import TextIO
2026-07-14 16:30:36 +08:00
def _set_console_title(title: str) -> None:
if os.name == "nt":
ctypes.windll.kernel32.SetConsoleTitleW(title)
2026-10-09 09:12:14 +08:00
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
2026-07-14 16:30:36 +08:00
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)
2026-10-09 09:12:14 +08:00
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
2026-07-14 16:30:36 +08:00
for line in process.stdout:
2026-10-09 09:12:14 +08:00
if not _write_console(console_output, line):
console_output = None
2026-07-14 16:30:36 +08:00
log_file.write(line)
log_file.flush()
return process.wait()
2026-10-09 09:12:14 +08:00
except KeyboardInterrupt:
if process is None:
return 1
process.terminate()
return process.wait()
2026-10-10 16:35:29 +08:00
except OSError as exc:
message = f"无法启动服务命令 {command[0]}: {exc}\n"
_write_console(console_output, message)
try:
with log_path.open("a", encoding="utf-8") as log_file:
log_file.write(message)
except OSError:
pass
return 1
2026-10-09 09:12:14 +08:00
finally:
if process is not None and process.stdout is not None:
2026-07-14 16:30:36 +08:00
process.stdout.close()
2026-10-09 09:12:14 +08:00
try:
pid_path.unlink()
except FileNotFoundError:
pass
if opened_console_output is not None:
opened_console_output.close()
2026-07-14 16:30:36 +08:00
if __name__ == "__main__":
raise SystemExit(main())