Python
Linux
console
window width
programming

How to get Linux console window width in Python

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When a Python program formats output for a terminal, it often needs to know how many columns are currently available. The simplest and most portable answer on modern Python is shutil.get_terminal_size(), with fallback handling for cases where the program is not attached to a real terminal.

python
1import shutil
2
3size = shutil.get_terminal_size(fallback=(80, 24))
4print(size.columns)
5print(size.lines)

This returns a os.terminal_size object with columns and lines. The fallback matters because many programs run in environments where standard output is redirected or where no interactive terminal exists.

os.get_terminal_size Works Too

If you want the lower-level call directly, use os.get_terminal_size.

python
1import os
2import sys
3
4size = os.get_terminal_size(sys.stdout.fileno())
5print(size.columns)

This is fine when you know the file descriptor belongs to a terminal. If it does not, Python raises OSError.

Handle Non-TTY Environments Explicitly

Programs do not always run in an interactive shell. They may run under cron, CI, pipes, or output redirection.

python
1import shutil
2import sys
3
4if sys.stdout.isatty():
5    width = shutil.get_terminal_size().columns
6else:
7    width = 80
8
9print(width)

That pattern avoids exceptions and gives your application a predictable fallback width.

Why Fallback Behavior Matters

If your code assumes a terminal always exists, it can crash when someone pipes output to a file.

bash
python app.py > output.txt

In that situation, stdout is no longer an interactive terminal device. Your formatting code should degrade gracefully instead of failing just because it cannot measure a screen width.

Environment Variables Are Not The Best Primary Source

Some terminal-aware tools export COLUMNS and LINES, but relying on those variables directly is less robust than using the standard library call, because they may be missing or stale.

python
import os

print(os.environ.get("COLUMNS"))

They can still be useful as a fallback or debugging clue, but not usually as your first choice.

Why stty size Is Usually Unnecessary

You can fetch terminal size through subprocess calls such as stty size, but that is usually slower and less reliable than the standard library.

python
1import subprocess
2
3result = subprocess.run(["stty", "size"], capture_output=True, text=True, check=True)
4rows, cols = map(int, result.stdout.split())
5print(cols)

This works in some shells, but it depends on external commands and can fail in containerized or non-interactive environments. Prefer shutil.get_terminal_size() unless you have a specific reason not to.

Wrapping Output Based On Width

Once you have the width, you can format output accordingly.

python
1import shutil
2import textwrap
3
4width = shutil.get_terminal_size(fallback=(80, 24)).columns
5message = "Python terminal applications often look better when they wrap to the current console width."
6print(textwrap.fill(message, width=width))

This is a simple example, but the same value can drive progress bars, tables, and TUI layouts.

Linux-Specific Versus Portable Code

The question often mentions Linux, but the standard-library approaches above are not Linux-only. That is usually a good thing. Unless you truly need Linux-specific terminal ioctls, portable code is easier to test and maintain.

Common Pitfalls

The most common mistake is calling os.get_terminal_size() in a non-terminal environment and not handling OSError. Another is assuming redirected output still has a console width in the interactive sense. Developers also sometimes use stty or environment variables as the primary solution even though the standard library already handles the common cases better. Finally, if your application caches the width forever, it may ignore terminal resize events during long-running sessions.

Summary

  • 'shutil.get_terminal_size(fallback=(80, 24)) is the simplest recommended solution.'
  • 'os.get_terminal_size works when you know you have a real terminal file descriptor.'
  • Always consider non-interactive environments such as pipes, cron, and CI.
  • Avoid depending on external commands like stty unless necessary.
  • Use a fallback width so console formatting remains stable even without a TTY.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.