Skip to content

Instantly share code, notes, and snippets.

@detly
Created March 15, 2015 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save detly/2ca59e57ffe177e1ad77 to your computer and use it in GitHub Desktop.
Save detly/2ca59e57ffe177e1ad77 to your computer and use it in GitHub Desktop.
pexpect.ANSI demo
#!/usr/bin/env python2
"""
Copyright (c) 2015, Jason Heeris
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
import fcntl
import os
import pty
import subprocess
import struct
import termios
import time
import pexpect.ANSI
# Don't rely on inheriting dimensions from the user's terminal.
SUBJECT_ROWS = 24
SUBJECT_COLS = 80
# Psuedo-terminal FDs
fd_master, fd_slave = pty.openpty()
# From ptyprocess source.
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
ioctl_struct = struct.pack('HHHH', SUBJECT_ROWS, SUBJECT_COLS, 0, 0)
fcntl.ioctl(fd_slave, TIOCSWINSZ, ioctl_struct)
# Start 'top'
top_proc = subprocess.Popen(
['top'],
stdin=fd_slave, stdout=fd_slave, stderr=subprocess.STDOUT,
close_fds=True)
# Just kill it after a couple of seconds, by sending the 'q' keystroke.
time.sleep(2)
os.write(fd_master, 'q')
top_proc.wait()
print("Process ended.")
# Read output into a buffer
output_buffer = b''
read_size = None
os.close(fd_slave)
try:
while (read_size is None) or (read_size > 0):
chunk = os.read(fd_master, 1024)
output_buffer += chunk
read_size = len(chunk)
print("Read: {:d}".format(read_size))
except OSError as io_error:
pass
print("Output buffer size: {:d}".format(len(output_buffer)))
# Render the result with pexpect's ANSI terminal emulator.
ansi_term = pexpect.ANSI.ANSI(SUBJECT_ROWS, SUBJECT_COLS)
ansi_term.write(output_buffer)
print(ansi_term)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment