How to read a single character from the user?

后端 未结 23 2783
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 04:28

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()).

23条回答
  •  我寻月下人不归
    2020-11-21 05:10

    The accepted answer didn't perform that well for me (I'd hold a key, nothing would happen, then I'd press another key and it would work).

    After learning about the curses module, it really seems like the right way to go. And it's now available for Windows through windows-cursors (available through pip), so you can program in a platform agnostic manner. Here's an example inspired by this nice tutorial on YouTube:

    import curses                                                                                                                                       
    def getkey(stdscr):
        curses.curs_set(0)
        while True:
            key = stdscr.getch()
            if key != -1:
                break
        return key
    
    if __name__ == "__main__":
        print(curses.wrapper(getkey))
    

    Save it with a .py extension, or run curses.wrapper(getkey) in interactive mode.

提交回复
热议问题