61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Run one Holmes interactive investigation on a PTY, then exit after its report."""
|
|
import os
|
|
import pty
|
|
import select
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 4 or sys.argv[2] != "--":
|
|
raise ValueError("usage: doctor-holmes-interactive.py CONVERSATION -- COMMAND [ARGS...]")
|
|
conversation = Path(sys.argv[1])
|
|
master, slave = pty.openpty()
|
|
child = subprocess.Popen(sys.argv[3:], stdin=slave, stdout=slave, stderr=slave, start_new_session=True)
|
|
os.close(slave)
|
|
exiting = False
|
|
|
|
def terminate(_signum, _frame):
|
|
try:
|
|
os.killpg(child.pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
raise SystemExit(124)
|
|
|
|
signal.signal(signal.SIGTERM, terminate)
|
|
signal.signal(signal.SIGINT, terminate)
|
|
try:
|
|
while child.poll() is None:
|
|
ready, _, _ = select.select([master], [], [], 0.2)
|
|
if ready:
|
|
try:
|
|
chunk = os.read(master, 65536)
|
|
except OSError:
|
|
break
|
|
if chunk:
|
|
sys.stdout.buffer.write(chunk)
|
|
sys.stdout.buffer.flush()
|
|
if not exiting and conversation.is_file() and conversation.stat().st_size:
|
|
os.write(master, b"/exit\n")
|
|
exiting = True
|
|
returncode = child.wait()
|
|
if not exiting and returncode == 0:
|
|
print("Holmes exited without saving a completed conversation.", file=sys.stderr)
|
|
return 1
|
|
return returncode
|
|
finally:
|
|
if child.poll() is None:
|
|
terminate(signal.SIGTERM, None)
|
|
os.close(master)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
sys.exit(main())
|
|
except (OSError, ValueError) as exc:
|
|
print(f"Holmes interactive runner: {exc}", file=sys.stderr)
|
|
sys.exit(1)
|