0

I am trying to write a program that captures at any time which key is being pressed. The ultimate goal is to control a robot from the keyboard, e.g. using wasd keys to control movement. It's rather easy using pygame, but as I want to be able to access my robot over SSH, I am looking for a purely bash-based solution. The curses library seems to be the way to go (but please let me know if there is a better solution). I now have something like this:

import curses


def main(screen):
    screen.timeout(50)
    key = ''
    while key != 'q':
        try:
            key = screen.getkey()
            screen.addstr(0, 0, 'key: {:<10}'.format(key))
        except:
            screen.addstr(0, 0, 'key: {:<10}'.format('N/A'))                    


if __name__ == '__main__':
    curses.wrapper(main)

which largely works fine, except for some unexpected behaviour: when I press and hold a key, it very briefly (and only once) alternates between the key in question and the 'N/A' fallback, as if I press and release and then press and hold.

I think my issue is caused by the character repeat delay setting on my machine. Indeed, if I increase the curses timeout setting to half a second, the problem is 'solved', but I want my program to be more responsive than half a second. Any way I can overrule the character repeat delay within my program? Or alternative solutions?

Note: Not sure if this is relevant, but I am using bash on Windows 10 (WSL) for testing purposes, and would ultimately like to run it on Raspbian.

NiH
  • 434
  • 6
  • 16
  • 2
    **NEVER** use a bare `except:`. It hides way too many exception and *will* create bugs in your code. Replace it with `except Exception as e: print(e)` to see what's happening. – Giacomo Alzetta Jan 21 '20 at 14:49
  • @GiacomoAlzetta , `getkey()` throws an exception when no key is pressed. I used the bare `except:` for quick testing purposes only, but obviously don't intend to keep it that way. Thanks for the remark though. – NiH Jan 21 '20 at 14:57
  • Have you checked [this question](https://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal) out? – Xosrov Jan 21 '20 at 15:23

0 Answers0