Best way of finding terminal width/height?

Grant Edwards grante at visi.com
Sun Feb 5 09:37:44 EST 2006


On 2006-02-05, Joel Hedlund <joel.hedlund at gmail.com> wrote:

> 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?

The way used in the code you found. Alternatively, yould use
ncurses, but that's massive overkill if all you want is the
terminal window size.

> 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.

Which details?  We'd be happy to explain the code.  Not that
you need to understand the details to use the code.

> How cross-platform is this?

It will work on any Unix system you're likely to encounter.  I
know it works on BSD, Solaris, and Linux.  I no longer yave
acces to a v7 system, but I'm pretty sure it would have worked
on that as well -- except the one I used didn't have a large
enough address space or disk drive to run Python.

I don't know if it will work on MS Windows or not.

> Is there a more pythonic way of  doing this?

What's unpythonic about the example you found?  It looks
extremely pythonic to me. The use of the "or" operator when
making ioctl calls and the try/except block when opening a file
is classically pythonic.

> Say something like:
>
> from ingenious_module import terminal_info
> cols, rows = terminal_info.size()

If that's what you want, put the code you found in to a file
named "ingenious_module.py".  I don't see the point of of
layering the namespace like that, though.  Just call it
terminal_info.py and do

import terminal_info
cols,rows = terminal_info.terminal_size()

-- 
Grant Edwards                   grante             Yow!  Oh, FISH sticks,
                                  at               CHEEZ WHIZ, GIN fizz,
                               visi.com            SHOW BIZ!!



More information about the Python-list mailing list