How to get Linux console window width in Python
pythonterminallinuxconsole
Abstraction: Python methods to query terminal console column width at runtime
Key points:
- Python 3.3+ canonical approach:
shutil.get_terminal_size()oros.get_terminal_size(); shutil wraps os with fallback but breaks when piping — useos.get_terminal_size(0)with stdin fd to handle pipes - Pre-3.3 approach:
os.popen('stty size', 'r').read().split()gives rows and columns;os.environ["COLUMNS"]is stale after terminal resize - Low-level approach uses
fcntl.ioctl(fd, termios.TIOCGWINSZ, ...)with struct unpack'hh'(signed) or'HHHH'(unsigned) depending on platform; must try stdin/stdout/stderr fds in order - Cross-platform (Linux/macOS/Windows/Cygwin) implementations exist using ctypes for Windows (GetConsoleScreenBufferInfo) and ioctl for POSIX; default fallback is (80, 25)
- Python
cursesmodule providesw.getmaxyx()as an alternative;blessingslibrary offersTerminal().widthas a high-level wrapper
Connections: Python Programming · Terminal IO
Source: http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python