Is shutil.get_terminal_size useless?

Peter Otten __peter__ at web.de
Sat Jan 28 07:53:55 EST 2017


Steve D'Aprano wrote:

>> 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)
> 
> Unless your terminal *actually is* 123 columns wide, I don't see that as
> an advantage. 

But the script does not write to the terminal and has no way (?) of knowing 
whether the pipe ends in the terminal or in a file.

Assuming it does end in the terminal seems like a good default to me, and 
setting COLUMNS provides a uniform way to override that default.

I prefer that to what e. g. aptitude does which uses the full width of the 
terminal window but falls back to 80

$ aptitude search foo
p   bygfoot                      - Fußball-Managerspiel                 
...

$ aptitude search foo | grep python
p   python-foolscap                 - RPC-System auf Basis der 
Objektfähigkeiten
p   python-rfoo                     - Fast RPC package for Python (and a

To get back well-behaved output you need both the envvar and a commandline 
option:

$ aptitude search -w $COLUMNS foo | grep python
p   python-foolscap              - RPC-System auf Basis der Objektfähigk

> I see that as "Hey look, we can fool shutil into returning
> absolute garbage instead of the terminal size!"

There are valid reasons for temporarily altering the number of columns, like 
writing to a file or preparing a code sample.

> I can already read environment variables using os.getenv() and os.environ,
> so this gives me no new functionality.
 
shutil.get_terminal_size()

combines access to shell variables and the os, and IMHO that is a useful 
approach.



More information about the Python-list mailing list