Fix packaged service console output

This commit is contained in:
王鹏
2026-10-09 09:12:14 +08:00
parent 3116ba81c5
commit e69c05d1d2
2 changed files with 90 additions and 25 deletions

View File

@@ -7,6 +7,7 @@ import os
import subprocess
import sys
from pathlib import Path
from typing import TextIO
def _set_console_title(title: str) -> None:
@@ -14,6 +15,26 @@ def _set_console_title(title: str) -> None:
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="后台服务")
@@ -39,36 +60,45 @@ def main() -> int:
executable = Path(command[0])
if executable.name.lower() in {"catalina.bat", "catalina.sh"} and executable.exists():
environment["CATALINA_HOME"] = str(executable.parent.parent)
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
try:
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:
print(line, end="", flush=True)
if not _write_console(console_output, line):
console_output = None
log_file.write(line)
log_file.flush()
return process.wait()
except KeyboardInterrupt:
process.terminate()
return process.wait()
finally:
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
try:
pid_path.unlink()
except FileNotFoundError:
pass
if opened_console_output is not None:
opened_console_output.close()
if __name__ == "__main__":