Files
makronix/tools/vmmon.py
T

56 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""vmmon.py -- run a qemu monitor command, print only the answer.
The monitor echoes every character it reads, so a plain read buries the one
line that matters ("OK" or "Error: ...") under a screenful of keystroke echo.
This prints the last lines with the echo and the escape noise removed.
vmmon.py --sock build/vm/monitor.sock device_add virtio-scsi-pci,id=scsihw
"""
import argparse
import re
import socket
import time
def run(sock, cmd, wait=0.8):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sock)
s.settimeout(2)
try:
s.recv(65536)
except OSError:
pass
s.sendall((cmd + "\n").encode())
time.sleep(wait)
out = b""
try:
while True:
chunk = s.recv(65536)
if not chunk:
break
out += chunk
except OSError:
pass
s.close()
text = re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", out.decode("utf-8", "replace"))
text = text.replace("\r", "")
lines = []
for line in text.split("\n"):
# the echo repeats the command character by character; drop it
if cmd and line.replace("(qemu) ", "").strip() and \
cmd.replace(" ", "") in line.replace(" ", ""):
continue
if line.strip() and line.strip() != "(qemu)":
lines.append(line.strip())
return "\n".join(lines[-4:]) or "(no answer)"
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--sock", default="build/vm/monitor.sock")
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args()
print(run(a.sock, " ".join(a.cmd)))