On Sat, 28 Jan 2017 19:03:42 +1100, 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@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@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
I can suggest a third approach to try but I have not tried piping it. YMMV. import fcntl import os import struct import termios tty = os.open(os.ctermid(), os.O_RDONLY) ts = struct.unpack("hh", fcntl.ioctl(tty, termios.TIOCGWINSZ, "1234")) os.close(tty) columns = ts[1] rows = ts[0] print(str(columns) + "x" + str(rows)) -- <Wildman> GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list