Search code examples
pythonkeypressncursescursesgetchar

Get just one char from long keypress python curses [accepted]


Hi I'm writing a program in python curses and I need to get just one char from a long keypress. (In other words what I need is that if i keep pressing down a key my program just has to get the char with the function getchar() just once). I need that because I want to prevent curses refreshing many times the windows. I'm not giving the code cause it is in italian and it is very long. Thank you.


Solution

  • One normally solves this problem by

    1. setting a variable which will record the fact that a character was read
    2. reading the character
    3. if no character is available (within a timeout, for instance), stop reading
    4. if no character was read yet, record the fact that one was read (as well as remembering which character)
    5. go back to step 2, to read again

    Simply reading from the terminal will not cause curses to do extra work (it does a refresh on each read, anyway). It would only have work to do if your program modifies the screen. So (assuming you have turned echo off), there is no need to worry about the number of calls to refresh.

    Regarding the comment "it has to clear and refresh the box": there are choices (per documentation):

    • window.erase() clears a window, but
    • window.clear() is like erase(), but also causes the whole window to be repainted upon next call to refresh().

    Avoid using window.clear() unless you intend repainting the whole window, because it is much slower, and is visually distracting.

    By the way, the curses function is called getch, not getchar. The latter may not work properly with curses.