Python input single character without enter

后端 未结 2 422
半阙折子戏
半阙折子戏 2020-12-11 16:25

What I am trying to do is make a simple pi memorization game in Python. What I need is a way to get input from the user without having to press \'enter\' after every charac

2条回答
  •  情深已故
    2020-12-11 17:05

    You can define your own version of getch using the termios, sys and tty packages:

    def getch():
        import termios
        import sys, tty
        def _getch():
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(fd)
                ch = sys.stdin.read(1)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch
        return _getch()
    

提交回复
热议问题