Created
August 9, 2022 12:00
-
-
Save chenzhuoyu/3e3785e6642883c28d19a6900498dba2 to your computer and use it in GitHub Desktop.
`resize` tool without installing `xterm`
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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import re | |
import os | |
import sys | |
import tty | |
import fcntl | |
import struct | |
import termios | |
SIZE_RE = re.compile('\x1b\\[8;(\\d+);(\\d+)t') | |
def resize(): | |
fd = sys.stdin.fileno() | |
sa = termios.tcgetattr(fd) | |
# resize under cbreak mode | |
try: | |
tty.setcbreak(fd) | |
resize_to_fit(fd, sys.stdout.fileno()) | |
finally: | |
termios.tcsetattr(fd, termios.TCSADRAIN, sa) | |
def resize_window(fd, row, col): | |
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HH4x", row, col)) | |
def resize_to_fit(stdin, stdout): | |
os.write(stdout, b'\x1b[18t') | |
ret = SIZE_RE.match(os.read(stdin, 65536).decode('utf-8')) | |
resize_window(stdout, int(ret.group(1)), int(ret.group(2))) | |
if __name__ == '__main__': | |
resize() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment