Skip to content

Instantly share code, notes, and snippets.

@geraintwhite
Created November 12, 2014 10:10
Show Gist options
  • Save geraintwhite/9a2666e1686d5ff373e2 to your computer and use it in GitHub Desktop.
Save geraintwhite/9a2666e1686d5ff373e2 to your computer and use it in GitHub Desktop.
Python module to get terminal size
import sys
def getTerminalSize():
import os
env = os.environ
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except:
return
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
return int(cr[1]), int(cr[0])
def supported_chars(*tests):
"""
Takes any number of strings, and returns the first one
the terminal encoding supports. If none are supported
it returns '?' the length of the first string.
"""
for test in tests:
try:
test.encode(sys.stdout.encoding)
return test
except UnicodeEncodeError:
pass
return '?' * len(tests[0])
WIDTH, HEIGHT = getTerminalSize()
CLS = chr(27) + '[2J'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment