examples/terminal_job.py

Source at 4d73c9795adca3e49eea74d1d2cbbbbdcbea0b6c

SHA-256: 91174938faf91d788f21eb06bfd4a96ee41dfcb0ca140c96f4fdf45f03998d74

#!/usr/bin/env python3
"""Finish only after the terminal parser acknowledges all preceding output."""

import os
import select
import sys
import termios
import time
import tty


def main():
    fd = sys.stdin.fileno()
    original = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        # The reply is generated by tmux after parsing the preceding output.
        os.write(sys.stdout.fileno(), b"build complete\r\n\x1b[5n")
        deadline = time.monotonic() + 0.9
        reply = b""
        while len(reply) < 4:
            remaining = deadline - time.monotonic()
            if remaining <= 0 or not select.select([fd], [], [], remaining)[0]:
                raise RuntimeError("terminal did not acknowledge output")
            part = os.read(fd, 4 - len(reply))
            if not part:
                raise RuntimeError(
                    "terminal closed before acknowledging output"
                )
            reply += part
        if reply != b"\x1b[0n":
            raise RuntimeError("unexpected terminal acknowledgement")
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, original)


if __name__ == "__main__":
    try:
        main()
    except RuntimeError as error:
        os.write(sys.stderr.fileno(), (str(error) + "\n").encode())
        raise SystemExit(1)