Is shutil.get_terminal_size useless?

Steve D'Aprano steve+python at pearwood.info
Sat Jan 28 03:03:42 EST 2017


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?


Thanks to Bernardas Ališauskas:

http://granitosaurus.rocks/getting-terminal-size.html


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list