How to Get Terminal Size in Python
The terminal is among the most popular and powerful tools for us devs and geeks. It allows us to perform automated tasks even in environments without a graphical interface.
However, did you know that the terminal has dimensions? The terminal window contains a set of units that govern the width and height of the text-based Window. This will, in turn, govern the content that can fit the screen, when to break the content, and such.
The number of rows and columns usually governs most terminal window dimensions.
- rows - The number of rows defines the number of text that can fit in a vertical window. Each row can accommodate a specific number of characters before wrapping to the following line.
- columns - On the other hand, are used to depict the number of characters that can be displayed horizontally in each row of the terminal. This determines the maximum width of the text you can see on a single line before it wraps to the next one.
When creating terminal-based applications, getting the terminal size can be essential, allowing you to create and adjust the content dynamically.
In this tutorial, we will learn how to use the provided Python features to the dimensions of a given terminal Window and some practical examples to cement the knowledge.
Using the os
Module with stty
Command
The first and most common method that we can use is the stty
command from Python’s os
module. This command allows us to fetch the terminal dimensions.
An example usage is as shown:
>>> import os
>>> rows, columns = os.popen('stty size', 'r').read().split()
>>> rows, columns = int(rows), int(columns)
>>> print(f"Terminal Rows: {rows}, Columns: {columns}")
In this case, we use the the popen
method to get the terminal size. The stty size
is a command available in all Unix-based systems to get the size of the current terminal.
We then convert the resulting values into integers and print them out as shown in the output below:
Terminal Rows: 15, Columns: 281
Using the shutil
Module with get_terminal_size()
We can use the get_terminal_size()
method from Python’s shutil
module to fetch the terminal dimensions.
An example is as shown:
>>> import shutil
>>> cols, rows = shutil.get_terminal_size()
>>> print(f"Terminal Rows: {rows}, Columns: {cols}")
Output:
Terminal Rows: 15, Columns: 281
Using ANSI Escape Codes
We can also take advantage of ANSI escape codes to query the terminal dimensions with some basic parsing. An example is as shown:
import sys
import fcntl
import termios
import struct
try:
rows, cols = struct.unpack('hh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234'))
print(f"Terminal Rows: {rows}, Columns: {cols}")
except Exception:
print("Unable to determine terminal size.")
Output:
Terminal Rows: 15, Columns: 281
Example Usage - Create a Dynamic Progress Bar
To better demonstrate the usage of the terminal size, we will create a basic progress bar that dynamically adjusts to the size of the terminal.
The code is as shown:
import time
import os
def get_terminal_size():
rows, cols = os.popen('stty size', 'r').read().split()
return int(rows), int(cols)
def dynamic_progress_bar():
rows, cols = get_terminal_size()
if rows and cols:
for i in range(cols):
progress = (i + 1) / cols
bar_width = int(cols * progress)
bar = '-' * bar_width
spaces = ' ' * (cols - bar_width)
print(f"[{bar}{spaces}] {int(progress * 100)}%", end='\r')
time.sleep(0.1)
else:
print("Unable to determine terminal size.")
dynamic_progress_bar()
Running the code should create an elementary progress bar using ASCII characters.
Conclusion
In this post, we learned how to use Python’s feature to get the size of the current terminal Window in rows and columns. We also covered how to use it to create a basic dynamic progress bar.