Python input single character without enter

后端 未结 2 418
半阙折子戏
半阙折子戏 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()
    
    0 讨论(0)
  • 2020-12-11 17:05

    This is a tested (on RPi, Py 3) code that can read a specified length of chars without need to hit Enter button

    But consider one thing :

    This must run on terminal otherwise raises an error

    import termios, sys , tty
    def _getch():
       fd = sys.stdin.fileno()
       old_settings = termios.tcgetattr(fd)
       try:
          tty.setraw(fd)
          ch = sys.stdin.read(1)     #This number represents the length
       finally:
          termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
       return ch
    getch = _getch()
    print(getch)
    
    0 讨论(0)
提交回复
热议问题