Is shutil.get_terminal_size useless?

Peter Otten __peter__ at web.de
Sat Jan 28 03:39:57 EST 2017


Steve D'Aprano wrote:

> shutil.get_terminal_size returns the wrong values when you pipe your
> output to another process, even it you do so in a terminal. Consider this
> script:
> 
> 
> import os
> import shutil
> print('shutil:', shutil.get_terminal_size(fallback=(999, 999)))
> print('os:', os.get_terminal_size(0))
> 
> 
> That uses two different methods to get the terminal size. If I run that in
> a terminal in the normal way, it works fine, returning the correct size
> for my terminal:
> 
> 
> [steve at ando ~]$ python3.5 test_gts.py
> shutil: os.terminal_size(columns=116, lines=29)
> os: os.terminal_size(columns=116, lines=29)
> 
> 
> But if I pipe the output to something else, the shutil version fails to
> determine the correct terminal size, and falls back on the default:
> 
> 
> [steve at ando ~]$ python3.5 test_gts.py | cat
> shutil: os.terminal_size(columns=999, lines=999)
> os: os.terminal_size(columns=116, lines=29)
> 
> 
> while the os version gives the correct result.
> 
> Is shutil.get_terminal_size useless? When, if ever, should I use it in
> preference to the os version? If the shutil version is broken, can it be
> fixed?

One potential advantage of shutil.get_terminal_size() is that you can affect 
it with an environment variable:

$ python3 test_gts.py | cat
shutil: os.terminal_size(columns=999, lines=999)
os: os.terminal_size(columns=72, lines=48)

$ COLUMNS=123 python3 test_gts.py | cat
shutil: os.terminal_size(columns=123, lines=999)
os: os.terminal_size(columns=72, lines=48)

I have the line

export LINES COLUMNS

in my .bashrc, so by default I see the physical size:

$ export COLUMNS LINES
$ python3 test_gts.py | cat
shutil: os.terminal_size(columns=72, lines=48)
os: os.terminal_size(columns=72, lines=48)


> Thanks to Bernardas Ališauskas:
> 
> http://granitosaurus.rocks/getting-terminal-size.html




More information about the Python-list mailing list