Last active
April 24, 2024 21:44
-
-
Save secemp9/ab0ce0bfb0eaf73d831033dbfade44d9 to your computer and use it in GitHub Desktop.
Get terminal size in pixels using escape sequence (works on Linux and msys2/mingw)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import termios | |
import tty | |
def get_text_area_size(): | |
# Save the terminal's original settings | |
fd = sys.stdin.fileno() | |
original_attributes = termios.tcgetattr(fd) | |
try: | |
# Set the terminal to raw mode | |
tty.setraw(sys.stdin.fileno()) | |
# Query the text area size | |
print("\x1b[14t", end="", flush=True) | |
# Read the response (format: "\x1b[4;height;widtht") | |
response = "" | |
while True: | |
char = sys.stdin.read(1) | |
response += char | |
if char == "t": | |
break | |
# Parse the response to extract height and width | |
if response: | |
return tuple(map(int, response[:-2].split(';')[1:])) | |
else: | |
return None | |
finally: | |
# Restore the terminal's original settings | |
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes) | |
# Example usage | |
text_area_size = get_text_area_size() | |
if text_area_size: | |
print(f"Text area size is {text_area_size[0]} rows by {text_area_size[1]} columns") | |
else: | |
print("Failed to get text area size") |
@GiorgosXou Ah, you're right :) Updated it and tested, works.
@secemp9 it's actually [:-1]
not [:-2]
, my fault sorry. 😅
and to ensure comprehensive coverage, I recommend including the alternative method as well. (for future visitors)
...
else: # ... https://stackoverflow.com/a/43947507/11465149
buf = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(1, termios.TIOCGWINSZ, buf)
return (buf[3], buf[2])
Thanks :) appreciate that you cited the source
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should work fine instead of regex i think.