Best way of finding terminal width/height?



Hi all!

I use python for writing terminal applications and I have been bothered by how hard it seems to be to determine the terminal size. What is the best way of doing this?

At the end I've included a code snippet from Chuck Blake 'ls' app in python. It seems to do the job just fine on my comp, but regrettably, I'm not sassy enough to wrap my head around the fine grain details on this one. How cross-platform is this? Is there a more pythonic way of doing this? Say something like:

from ingenious_module import terminal_info
cols, rows = terminal_info.size()

Thanks for your time (and thanks Chuck for sharing your code!)
/Joel Hedlund
IFM Bioinformatics
Linköping University

Chuck Blake's terminal_size code snippet:
(from http://pdos.csail.mit.edu/~cblake/cls/cls.py).

def ioctl_GWINSZ(fd): #### TABULATION FUNCTIONS
try: ### Discover terminal width
import fcntl, termios, struct, os
cr = struct.unpack('hh',
fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
except:
return None
return cr

def terminal_size():
### decide on *some* terminal size
# try open fds
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
# ...then ctty
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
if not cr:
# env vars or finally defaults
try:
cr = (env['LINES'], env['COLUMNS'])
except:
cr = (25, 80)
# reverse rows, cols
return int(cr[1]), int(cr[0])
.



Relevant Pages

  • Re: Hooking windowsmessages with python
    ... I'm trying to set a message hook with python to catch WM_DROPFILES. ... Here a code snippet: ... def test: ...
    (comp.lang.python)
  • RE: PyNumber_Int screwing Object.
    ... > This code snippet is broken in the case that the argument passed is a ... That's incorrect use of the Python C API: the return value of every call ... made to a Python C API function must be checked for an error value, ... or return its own error value to its caller. ...
    (comp.lang.python)
  • Re: Question about optimization
    ... I'm pretty new to python and I have some optimization issues. ... so I search through the table in chunks given by delta ... I am 100% sure it's this code snippet that's the cause of my problems. ... takes to fetch the SQL query doesn't change. ...
    (comp.lang.python)
  • Re: scanning under windows WIA with custom settings (dpi / etc )
    ... I'm trying to scan a document from a python 2.6 script without user ... I found a code snippet, that allows me to scan under Vista, but that ... anything in windows is a real PITA! ...
    (comp.lang.python)
  • Re: Why is Lisp not as popular as Python?
    ... Or a code snippet is pasted into a mail message and ... Never happened in 7 years of python development. ... usually mailers don't scramble your mail. ... Python proved, in over 14 years of life, that a language can grow ...
    (comp.lang.lisp)

Loading