Created
September 28, 2011 13:41
-
-
Save brownan/1247961 to your computer and use it in GitHub Desktop.
Print the output of a command line command in hexdump format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import pty | |
import os | |
import subprocess | |
import string | |
""" | |
An example script to show how Python's pty module can be used to capture the | |
input of any console program. This script prints out each byte from its | |
subprocess in hexdump format. It's useful for debugging console interfaces that | |
have lots of control characters. | |
""" | |
printable = set(string.printable) - set(string.whitespace) | set(" ") | |
chrmap = { | |
'\x1b': '^', | |
'\n': '\\n', | |
'\r': '\\r', | |
'\t': '\\t', | |
"\x01": u"\N{BLACK STAR}".encode("UTF-8"), | |
"\x02": u"\N{WHITE STAR}".encode("UTF-8"), | |
} | |
# line is the most recently written line to the console | |
line = "" | |
def printhex(char): | |
global line | |
if len(line) == 16: | |
sys.stdout.write("\n") | |
line = "" | |
line += char | |
sys.stdout.write("\r") | |
for c in line[:8]: | |
sys.stdout.write("%02X " % ord(c)) | |
sys.stdout.write(" ") | |
for c in line[8:16]: | |
sys.stdout.write("%02X " % ord(c)) | |
sys.stdout.write(" ") | |
sys.stdout.write(" " * 3*(16-len(line))) | |
for c in line: | |
if c in printable: | |
sys.stdout.write(c) | |
elif c in chrmap: | |
sys.stdout.write(chrmap[c]) | |
else: | |
sys.stdout.write(u"?".encode("UTF-8")) | |
sys.stdout.flush() | |
def main(): | |
path = sys.argv[1] | |
arglist = sys.argv[2:] | |
master, slave = pty.openpty() | |
proc = subprocess.Popen([path]+arglist, | |
stdout=slave, stderr=slave) | |
os.close(slave) | |
while not proc.poll(): | |
try: | |
a = os.read(master, 1) | |
except OSError: | |
break | |
except KeyboardInterrupt: | |
continue | |
if not a: break | |
printhex(a) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment