Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize the terminal with Python?

I couldn't find anything with a quick Google search, nor anything on here, saving for this. However, it doesn't do the trick. So how exactly do you resize the terminal using Python?

like image 979
Elliot Bonneville Avatar asked Jun 20 '11 23:06

Elliot Bonneville


2 Answers

To change the tty/pty setting you have to use an ioctl on the stdin file descriptor.

import termios
import struct
import fcntl

def set_winsize(fd, row, col, xpix=0, ypix=0):
    winsize = struct.pack("HHHH", row, col, xpix, ypix)
    fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)

But to change the actual window size you can use terminal escape sequences, but not all terminals support or enable that feature. If you're using urxvt you can do this:

import sys
sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=32, cols=100))

But that may not work on all terminals.

like image 161
Keith Avatar answered Sep 20 '22 10:09

Keith


If you install xdotool, you can change the size of the terminal window with something like this:

import subprocess
import shlex

id_cmd='xdotool getactivewindow'
resize_cmd='xdotool windowsize --usehints {id} 100 30'

proc=subprocess.Popen(shlex.split(id_cmd),stdout=subprocess.PIPE)
windowid,err=proc.communicate()
proc=subprocess.Popen(shlex.split(resize_cmd.format(id=windowid)))
proc.communicate()

PS. On Ubuntu xdotool is provided by a package of the same name.

like image 22
unutbu Avatar answered Sep 21 '22 10:09

unutbu