Have you ever wondered how to get the current size of your terminal window from within a Python script? In Python, the os
module provides a convenient way to do so using the os.get_terminal_size()
function.
The os.get_terminal_size()
Function
The os.get_terminal_size()
function returns the size of the terminal window as a named tuple with columns
and lines
attributes representing the width and height of the terminal, respectively.
To use this function, you need to import the os
module first:
import os
Then, you can call the get_terminal_size()
function to retrieve the terminal size:
terminal_size = os.get_terminal_size()
Example Usage
Let’s see a simple example that prints the current size of the terminal window:
import os
def print_terminal_size():
terminal_size = os.get_terminal_size()
print(f"The current terminal size is {terminal_size.columns} columns by {terminal_size.lines} lines.")
print_terminal_size()
When you run the above code, it will output something like this:
The current terminal size is 80 columns by 24 lines.
Compatibility Note
Please note that os.get_terminal_size()
is available in Python 3.3 and later versions. If you are using an older version of Python, you may need to consider an alternative method or upgrade your Python installation.
Conclusion
Obtaining the size of the terminal window can be useful when developing command-line applications or scripts that require adaptive rendering. The os.get_terminal_size()
function in Python provides a straightforward way to retrieve this information.