Python Curses Handling Window (Terminal) Resize Python Curses Handling Window (Terminal) Resize python python

Python Curses Handling Window (Terminal) Resize


Terminal resize event will result in the curses.KEY_RESIZE key code. Therefore you can handle terminal resize as part of a standard main loop in a curses program, waiting for input with getch.


I got my python program to re-size the terminal by doing a couple of things.

# Initialize the screenimport cursesscreen = curses.initscr()# Check if screen was re-sized (True or False)resize = curses.is_term_resized(y, x)# Action in loop if resize is True:if resize is True:    y, x = screen.getmaxyx()    screen.clear()    curses.resizeterm(y, x)    screen.refresh()

As I'm writing my program I can see the usefulness of putting my screen into it's own class with all of these functions defined so all I have to do is call Screen.resize() and it would take care of the rest.


I use the code from here.

In my curses-script I don't use getch(), so I can't react to KEY_RESIZE.

Therefore the script reacts to SIGWINCH and within the handler re-inits the curses library. That means of course, you'll have to redraw everything, but I could not find a better solution.

Some example code:

from curses import initscr, endwinfrom signal import signal, SIGWINCHfrom time import sleepstdscr = initscr()def redraw_stdscreen():    rows, cols = stdscr.getmaxyx()    stdscr.clear()    stdscr.border()    stdscr.hline(2, 1, '_', cols-2)    stdscr.refresh()def resize_handler(signum, frame):    endwin()  # This could lead to crashes according to below comment    stdscr.refresh()    redraw_stdscreen()signal(SIGWINCH, resize_handler)initscr()try:    redraw_stdscreen()    while 1:        # print stuff with curses        sleep(1)except (KeyboardInterrupt, SystemExit):    passexcept Exception as e:    passendwin()