Skip to content

Instantly share code, notes, and snippets.

@chenzhuoyu
Created August 9, 2022 12:00
Show Gist options
  • Save chenzhuoyu/3e3785e6642883c28d19a6900498dba2 to your computer and use it in GitHub Desktop.
Save chenzhuoyu/3e3785e6642883c28d19a6900498dba2 to your computer and use it in GitHub Desktop.
`resize` tool without installing `xterm`
#!/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