Skip to content

Instantly share code, notes, and snippets.

@secemp9
Last active April 24, 2024 21:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secemp9/ab0ce0bfb0eaf73d831033dbfade44d9 to your computer and use it in GitHub Desktop.
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)
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
Copy link

GiorgosXou commented Mar 23, 2024

This should work fine instead of regex i think.

        if response:
            return response[:-2].split(';')[1:]
        else:
            return None

@secemp9
Copy link
Author

secemp9 commented Mar 23, 2024

@GiorgosXou Ah, you're right :) Updated it and tested, works.

@GiorgosXou
Copy link

@secemp9 it's actually [:-1] not [:-2], my fault sorry. 😅

@GiorgosXou
Copy link

GiorgosXou commented Mar 26, 2024

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])

@GiorgosXou
Copy link

@secemp9
Copy link
Author

secemp9 commented Apr 24, 2024

Back link - stackoverflow Q&A

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