[파이썬] shutil `shutil.get_terminal_size()`: 터미널 크기 가져오기

When developing command-line applications or scripts, understanding the size of the terminal window can be crucial for creating a user-friendly experience. Luckily, the shutil module in Python provides a convenient way to get the terminal size using the shutil.get_terminal_size() function.

Getting terminal size in Python

To determine the current size of the terminal in Python, you can use the shutil.get_terminal_size() function. This function returns a named tuple, which consists of two integer values representing the width and height of the terminal window.

Here’s an example of how to use the shutil.get_terminal_size() function:

import shutil

terminal_size = shutil.get_terminal_size()
width = terminal_size.columns
height = terminal_size.lines

print(f"Terminal width: {width} columns")
print(f"Terminal height: {height} lines")

By calling shutil.get_terminal_size(), we retrieve the current size of the terminal window. We then access the columns and lines attributes of the returned named tuple to get the width and height, respectively.

Handling terminal size changes

It’s worth noting that the terminal size can change dynamically while your program is running. To handle these changes, you can periodically check the terminal size using the shutil.get_terminal_size() function.

For example, you might want to continuously adjust the layout or formatting of your application based on the terminal width. By periodically getting the terminal size, you can adapt your program to fit the available space and improve the user experience.

import shutil
import time

while True:
    terminal_size = shutil.get_terminal_size()
    width = terminal_size.columns

    if width < 80:
        print("Warning: Terminal width is less than 80 columns.")

    time.sleep(1)  # Delay to avoid excessive checking

In the example above, we continuously check the terminal width using a while loop. If the width is less than 80 columns, we print a warning message. The time.sleep(1) statement adds a delay of 1 second between each terminal size check to prevent excessive resource usage.

Conclusion

The shutil.get_terminal_size() function in the shutil module provides an easy way to retrieve the current size of the terminal window in Python. Understanding the terminal size can be useful for creating responsive command-line applications and improving the user experience. By periodically checking the terminal size, you can adapt your program to fit the available space and cater to different terminal configurations.