get the terminal's size

Grant Edwards grant.b.edwards at gmail.com
Mon Jan 14 10:19:51 EST 2019


On 2019-01-14, Peter Otten <__peter__ at web.de> wrote:
>
>> I want to know the number of columns of the terminal where python2 writes
>> it's outputs.
>> 
>> In a terminal, I type
>> $ echo $COLUMNS
>> 100
>> 
>> But in Python, os.getenv("COLUMNS") gets nothing.
>> It gets nothing as well if I try to read the output of "echo $COLUMNS"
>> from a subprocess.
[...]
> If you see similar output consider adding
>
> export COLUMNS LINES
>
> to your .bashrc or equivalent.

That will tell you the terminal size at the time Python was started.

If the terminal size has changed while Python was running, those
environment variables will be wrong.  You need to use the TIOCGWINSZ
ioctl call:

    http://www.delorie.com/djgpp/doc/libc/libc_495.html

And to detect the size changes (so you know _when_ you need to do the
above), you need to attach a signal handler for the WINCH signal.

-- 
Grant Edwards               grant.b.edwards        Yow! Should I do my BOBBIE
                                  at               VINTON medley?
                              gmail.com            




More information about the Python-list mailing list