How to read a single character from the user?

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

    This might be a use case for a context manager. Leaving aside allowances for Windows OS, here's my suggestion:

    #!/usr/bin/env python3
    # file: 'readchar.py'
    """
    Implementation of a way to get a single character of input
    without waiting for the user to hit .
    (OS is Linux, Ubuntu 14.04)
    """
    
    import tty, sys, termios
    
    class ReadChar():
        def __enter__(self):
            self.fd = sys.stdin.fileno()
            self.old_settings = termios.tcgetattr(self.fd)
            tty.setraw(sys.stdin.fileno())
            return sys.stdin.read(1)
        def __exit__(self, type, value, traceback):
            termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)
    
    def test():
        while True:
            with ReadChar() as rc:
                char = rc
            if ord(char) <= 32:
                print("You entered character with ordinal {}."\
                            .format(ord(char)))
            else:
                print("You entered character '{}'."\
                            .format(char))
            if char in "^C^D":
                sys.exit()
    
    if __name__ == "__main__":
        test()
    

提交回复
热议问题