Is shutil.get_terminal_size useless?

Michael Torrie torriem at
Sat Jan 28 11:44:54 EST 2017

On 01/28/2017 09:15 AM, Steve D'Aprano wrote:
> Then explain why os.get_terminal_size() returns the correct answer.

Basically you were asking two different questions there.
shutil.get_terminal_size always asks the question of size of the
terminal that the standard output file handle is connected to.  Whereas,
if I read this correctly, you asked os.get_terminal_size to query the
size of the terminal attached to the *standard input* file handle. These
are very different things.  If you want to know the size of the terminal
on the input side, use os.get_terminal_size(0), not shutil.

By the way my comment about raising an exception a moment ago was about
os.get_terminal_size(1).  Apparently shutil is trying to be a
convenience function and lets you specify a default size if there is no
size to determine.

> The output might not be going to a terminal (not directly at least) but the
> question isn't "what's the size of the terminal that output is going to".
> The question is "what's the size of the terminal that this process is
> running in", and that has an answer regardless of where output is piped.

In your specific case, the answer is to get the terminal size by
querying os.get_terminal_size on standard in, since your standard out is
not a tty.

In most other situations the question doesn't make a lot of sense
because there's no correlation between the terminal that the process is
running in and the terminal the process's output is going to be piped to
when a tty is not involved.  For example:

command1 | python3 | command2

In that case your process has no terminal on either end.  Only command1
and command 2 do.

More information about the Python-list mailing list