When writing command-line applications in Python, it's often useful to know the size of the terminal window. Knowing the terminal dimensions allows you to format text output neatly, create progress bars that fit perfectly, and design user interfaces that respond to the available space. Python provides a built-in function to get the terminal's size, which you can use to make your programs more responsive and visually appealing.
In this guide, we'll learn how to obtain the terminal dimensions and demonstrate some practical applications for this information.
Table of Contents
Get the Size of the Terminal Window using Python
To get the size of the terminal your code is running on, you can use functions provided by libraries in Python such as os
and shutil
. The terminal size is typically represented by the number of rows (lines) and columns (characters per line).
Here's how you can do it using Python:
- Using
os.get_terminal_size()
: This function is available in Python 3.3 and later. - Using
shutil.get_terminal_size()
: This function is available in Python 3.3 and later, and it is more commonly recommended.
Here is an example code using shutil.get_terminal_size()
:
import shutil def get_terminal_size(): size = shutil.get_terminal_size() return size.columns, size.lines columns, rows = get_terminal_size() print(f"Terminal size: {columns} columns and {rows} rows")
Code Explanation:
- Import
shutil
: This module provides a high-level interface for file operations and includes theget_terminal_size()
function. - Define a function to get terminal size: The
shutil.get_terminal_size()
function returns a named tuple with two attributes:columns
andlines
. - Print the terminal size: The values for columns and rows are printed to the terminal.
This method is straightforward and effective for getting the terminal size in Python scripts.
Here is the output of the above Python code in my Debian system:
Terminal size: 80 columns and 24 rows
You can further simplify this code like below:
import shutil # Get the terminal size terminal_size = shutil.get_terminal_size() # Print the terminal size print(f"Terminal size: {terminal_size.columns} x {terminal_size.lines}")
The output of the above code is:
Terminal size: 80 x 24
In the above examples, I have run the code inside the Python interactive console. Because example code is shorter and simple.
You can also put the code in a text file or use any IDE and run it using the python
command.
To do so, open your favorite text editor or IDE and create a new file, e.g., terminal_size.py
. Copy one of the example code snippets provided above and paste it into the file.
Open your terminal and navigate to the directory where you saved terminal_size.py
. Run the script using the Python interpreter like below.
$ python3 terminal_size.py
For quick tests and learning, the Python console is very useful due to its immediate feedback and interactive nature.
For larger scripts or projects, organizing code into files and running them with the python
command is generally better. This method supports better code organization, reusability, reproducibility, and access to advanced editing tools.
Choosing between the two depends on the complexity of the task and your specific needs. For best practices in software development, writing code in files and using a good text editor or IDE is recommended.
Moving forward, I will put the code in a file and run it using python
command.
Some Practical Examples
Knowing the size of the terminal can be useful in various scenarios, especially when developing command-line applications or scripts that interact with the user.
Here are some common use cases:
1. Text Formatting: Ensuring that output is properly formatted to fit within the terminal window.
This is useful for avoiding line wraps and maintaining readability. For example, to print centered text, use the following example snippet:
import shutil def print_centered(text): columns, _ = shutil.get_terminal_size() print(text.center(columns)) print_centered("Hello, World!")
Run the code to print the text at the center of the terminal window:
$ python3 terminal_size.py Hello, World!
2. Dynamic UIs: Creating text-based user interfaces (TUIs) that adjust dynamically to the size of the terminal.
This is often used in tools like text editors, file managers, or dashboards. For example, the following code will draw box in your Terminal:
import shutil def draw_box(): columns, rows = shutil.get_terminal_size() print("+" + "-" * (columns - 2) + "+") for _ in range(rows - 2): print("|" + " " * (columns - 2) + "|") print("+" + "-" * (columns - 2) + "+") draw_box()
Run the code with command to draw a box:
$ python3 terminal_size.py
3. Progress Bars: Displaying progress bars that fill the width of the terminal window.
This is useful for showing the progress of tasks such as downloads or file processing.
import shutil import time def show_progress_bar(progress, total): columns, _ = shutil.get_terminal_size() bar_length = columns - 20 filled_length = int(bar_length * progress // total) bar = '█' * filled_length + '-' * (bar_length - filled_length) print(f'\rProgress: |{bar}| {progress}/{total}', end='\r') total = 100 for i in range(total + 1): show_progress_bar(i, total) time.sleep(0.1) print() # Move to the next line after completion
Running this code will display a progress bar in your Terminal window:
4. Logging and Debugging: Adjusting log output to fit within the terminal window, making it easier to read and understand logs during development or debugging.
Example code:
import shutil def log_message(message): columns, _ = shutil.get_terminal_size() if len(message) > columns: message = message[:columns - 3] + '...' print(message) log_message("This is a log message that will be truncated if it is too long for the terminal window.")
Code output:
5. Multi-Column Layouts: Creating outputs that are organized into multiple columns that fit the terminal width. This is useful for displaying lists or tables.
Sample code:
import shutil def print_columns(items, col_width=20): columns, _ = shutil.get_terminal_size() num_cols = columns // col_width for i in range(0, len(items), num_cols): print("".join(item.ljust(col_width) for item in items[i:i+num_cols])) items = ["Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"] print_columns(items)
Code output:
These simple examples show how knowing the terminal size can enhance the functionality and user experience of command-line applications by making output more adaptive and visually appealing.
Troubleshooting
If your Terminal size cannot be queried for any reason, you can handle the error gracefully by providing a default terminal size. For example:
import shutil def get_terminal_size(): try: size = shutil.get_terminal_size() except OSError: size = os.terminal_size((80, 24)) # Default size (80 columns, 24 rows) return size.columns, size.lines
In this case, the get_terminal_size
function takes an optional fallback
parameter, which defaults to (80, 24)
if not provided.
Frequently Asked Questions (FAQ)
A: Knowing the terminal size is useful for formatting output, creating dynamic user interfaces, displaying progress bars, logging messages, and designing text-based games. It helps ensure that your application's output fits well within the user's terminal window.
A: You can use the shutil.get_terminal_size()
function, which returns a named tuple with the number of columns and rows in the terminal.
shutil.get_terminal_size()
?A: The shutil.get_terminal_size()
function is available in Python 3.3 and later.
A: Yes, but you will need to use different methods or third-party libraries. For example, you can use the os
module with platform-specific commands or external libraries like blessed
.
A: Some practical applications include:
- Centering text output
- Creating dynamic text-based user interfaces
- Displaying progress bars that adjust to terminal width
- Formatting logs to fit the terminal window
- Designing text-based games or visualizations
A: You can periodically call shutil.get_terminal_size()
to check the current size of the terminal and adjust your output accordingly. This is especially useful in long-running scripts or applications where the terminal size might change during execution.
shutil.get_terminal_size()
?A: The main limitation is that it only works when a terminal is attached. If you run the script in an environment without a terminal (e.g., a background job or a service), it may raise an OSError
.
shutil.get_terminal_size()
raises an error?A: You can handle the error gracefully by providing a default terminal size. Please see Troubleshooting section above for details.
A: Yes, you can customize the default size by changing the values in os.terminal_size((80, 24))
to suit your needs.
Conclusion
In this tutorial, we learned how to query the terminal size with Python's built-in function in Linux and its use cases with a few practical examples.
Understanding the terminal size allows you to create more user-friendly command-line applications. By using the shutil.get_terminal_size()
function, you can easily adjust your program's output to fit the terminal window.
This makes your applications look better and work more efficiently. Whether you're centering text, drawing boxes, showing progress bars, logging messages, or printing columns, knowing the terminal size can significantly enhance your command-line interface design.
Resource: