get the terminal's size

Peter Otten __peter__ at web.de
Mon Jan 14 07:33:06 EST 2019


Alex Ternaute wrote:

> Hi there,
> 
> 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.
> 
> I feel that I'm missing something but what ?

$ python -c 'import os; print os.environ["COLUMNS"]'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'COLUMNS'
$ export COLUMNS
$ python -c 'import os; print os.environ["COLUMNS"]'
157

If you see similar output consider adding

export COLUMNS LINES

to your .bashrc or equivalent.

> Looking on the internet for a hint, I see that python3 has an
> os.get_terminal_size().
> Please, is there something similar for python2 ?
> 
> Cheers





More information about the Python-list mailing list