import re


def call_on_line(regexp, callback):
    """Returns a monitor that calls 'callback' when QEMU prints a line
    matching 'regexp'."""

    def setup_call_on_line(runner):
        buf = bytearray()
        def handle_output(output):
            buf.extend(output)
            while b"\n" in buf:
                line, buf[:] = buf.split(b"\n", 1)
                line = line.decode("utf-8", "replace")
                if re.match(regexp, line):
                    callback(line)
        runner.qemu.on_output.append(handle_output)
    return setup_call_on_line