Best way of finding terminal width/height?

Joel Hedlund joel.hedlund at gmail.com
Sun Feb 5 08:30:45 EST 2006


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])



More information about the Python-list mailing list