How to get terminal width?

Donn Cave donn at u.washington.edu
Wed May 3 18:46:56 CEST 2000


From: cpmcda01 at shark.kitenet.net [mailto:cpmcda01 at shark.kitenet.net]

| I need to write a command line script in Python that needs to  know the width
| of the terminal in characters. I've looked through several modules and
| haven't yet found what I'm looking for. Does anyone know where I need to
| look?

Contrary to popular belief, the COLUMNS environment variable isn't
universally available on UNIX platforms.  The last time I saw it was
on an obscure platform based on System V 3.2, and you don't get it
on contemporary Berkeley or Linux platforms, nor on commercial platforms
like Digital UNIX.

In C, you'd have access to an ioctl() that retrieves the data into a
struct, TIOCGWINSZ.  Python can call ioctl(), so that's an option,
but you may have to dig up the correct value for TIOCGWINSZ yourself.

    import fcntl
    import struct

    TIOCGWINSZ = 0x800c         # BeOS 4.5
    # TIOCGWINSZ = 0x40087468     # FreeBSD 4.0

    def ttysize():
        buf = 'abcdefgh'
        buf = fcntl.ioctl(0, 0x800c, buf)
        row, col, rpx, cpx = struct.unpack('hhhh', buf)
        return row, col

Since you can't rely on TIOCGWINSZ, the only other standard option I can
think of on UNIX is to read the output of "stty -a", where the first line
usually reports these values.  Empirically, I find that it always uses the
words "rows" and "columns" and there are ";" separators, but it could be
"rows 24" or "24 rows" depending on the platform:

    import os
    import string

    def ttysize():
        fp = os.popen('stty -a', 'r')
        ln1 = fp.readline()
        fp.close()
        if not ln1:
            raise ValueError, 'tty size not supported for input'
        vals = {'rows':None, 'columns':None}
        for ph in string.split(ln1, ';'):
            x = string.split(ph)
            if len(x) == 2:
                vals[x[0]] = x[1]
                vals[x[1]] = x[0]
        return vals['rows'], vals['columns']

Both of these approaches will work on reasonably modern platforms, but
that's still not everything.  stty is different on old BSD 4.2 platforms
like Ultrix, TIOCGWINSZ may not be supported on some old survivors.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list