0

I'm trying to write a function that would produce a simple widget when run in Python's console. This widget should be terminal-size-aware. After displaying the widget I will wait for user's keyboard input and adjust the content according to what the types. The difficulty that I have right now is how to make that widget adjust its display when the user resizes the terminal. Here's a simplified version of the code that I have right now:

def test():
    import blessed
    import signal

    def draw():
        n = term.width - 3
        print("+" + "=" * n + "+" + term.clear_eol)
        print("|" + " " * (n//2 - 2) + 
              "TEST" + " " * (n - n//2 - 2) + "|" + term.clear_eol)
        print("+" + "=" * n + "+" + term.clear_eol)

    def redraw(_, __):
        print(term.move_up * 3, end="")
        draw()

    term = blessed.Terminal()
    draw()
    signal.signal(signal.SIGWINCH, redraw)
    with term.cbreak():
        term.inkey()

This works fine if the user expands the terminal, or if he shrinks the terminal but very slowly (1 character at a time). However reducing the terminal width quickly will cause long lines to wrap, corrupting the output. Is there a way to address this problem?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Pasha
  • 6,298
  • 2
  • 22
  • 34
  • Possible duplicate of [How to get console window width in python](http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python) – nir0s Mar 13 '17 at 20:39

1 Answers1

0

The question refers to something like blessed 1.9.1, which asserts that it is a simplified wrapper to curses. Since Python curses provides support for repainting on SIGWINCH, the assertion would carry forward to this package. Actually the features described are for terminfo. curses does a lot more than that page shows.

To handle SIGWINCH using blessed, you'll have to catch that in your script and trigger a repaint of the screen. The example shown in Height and Width should be enough to get started.

Or you could use curses, where you'd do the repaint after reading a KEY_RESIZE from getch.

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • Thanks Thomas, however that does not help me to solve the problem. I tried `curses` at first, but the problem is that it puts terminal into the "fullscreen" mode (similar to `man` command), whereas I want my output to appear alongside all other output in the terminal. The `blessed` package does just that. And the only remaining problem is how to properly prevent line wraps when terminal is shrinking. – Pasha Mar 14 '17 at 22:19