pythonasync-await

Is there a way to getkey()/ getchar() asynchronously in python?


I need an asyncio compatible getkey() so I can

async def stuff():
    await getkey()

So when the coroutine stuff hits the await our loop stops the task, and continues on another one.

I am new to coding, but there sure is such a thing somewhere?

If not, is it possible to build such a coroutine? The getkey() could return the pressed key value in any form. But it should have cbreak and noecho on (don't wait for enter and don't print the pressed key).


I know that this way of doing it seems unusual. Curses running in its own thread would be the right way to go. But I can use curses only for displaying. Also, I am really new to coding.. and I have no time to look into this threading thing:/ I just need my 100 lines to work fluently, really fast and also only once :!


Solution

  • If you don't want to actually wait for the keypress, one way is to use a thread to detect the keypress:

    from threading import Thread
    import curses
    
    key_pressed = False
    
    def detect_key_press():
        global key_pressed
        stdscr = curses.initscr()
        key = stdscr.getch()
        key_pressed = True
    
    def main():
        thread = Thread(target = detect_key_press)
        thread.start()
        while not key_pressed:
            print('Hello world\r')
        curses.endwin()
    
    main()
    

    It's not exactly nice to use global variables, but it's a quick way to do it.