Python Glossary Русский

Python 3.3+osfunction

os.get_terminal_size

os — terminals and devices

Return the terminal size (columns, lines); raises OSError if not a terminal.

Syntax

os.get_terminal_size()

With output going to a file or pipe it raises OSError, so code that formats output to the terminal width crashes under redirection and in CI. Ordinary programs want shutil.get_terminal_size: it honours the COLUMNS and LINES variables and falls back to (80, 24) when there is no terminal.

Examples

import os
size = os.get_terminal_size()  # → ? только в терминале; в пайпе и CI — OSError
print(size)   # → os.terminal_size(columns=80, lines=24) — конкретные числа зависят от размеров окна терминала
print(size.columns)   # → ширина терминала в символах, например 80
print('-' * size.columns)   # → разделитель во всю ширину окна — типовое применение
print(os.get_terminal_size(0).lines)   # → высота терминала, привязанного к stdin (по умолчанию берётся stdout)
print(os.get_terminal_size(999))   # → OSError — дескриптор не привязан к терминалу; та же ошибка при запуске из пайпа или CI, поэтому в утилитах берут shutil.get_terminal_size() с запасным значением

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy