How to read a single character from the user?

后端 未结 23 2724
爱一瞬间的悲伤
爱一瞬间的悲伤 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:12

    This code, based off here, will correctly raise KeyboardInterrupt and EOFError if Ctrl+C or Ctrl+D are pressed.

    Should work on Windows and Linux. An OS X version is available from the original source.

    class _Getch:
        """Gets a single character from standard input.  Does not echo to the screen."""
        def __init__(self):
            try:
                self.impl = _GetchWindows()
            except ImportError:
                self.impl = _GetchUnix()
    
        def __call__(self): 
            char = self.impl()
            if char == '\x03':
                raise KeyboardInterrupt
            elif char == '\x04':
                raise EOFError
            return char
    
    class _GetchUnix:
        def __init__(self):
            import tty
            import sys
    
        def __call__(self):
            import sys
            import tty
            import termios
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                ch = sys.stdin.read(1)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch
    
    
    class _GetchWindows:
        def __init__(self):
            import msvcrt
    
        def __call__(self):
            import msvcrt
            return msvcrt.getch()
    
    
    getch = _Getch()
    

提交回复
热议问题