Skip to content

Instantly share code, notes, and snippets.

@secemp9
Last active April 24, 2024 21:44
Show Gist options
  • 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

@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