How to read a single character from the user?

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

    If I'm doing something complicated I'll use curses to read keys. But a lot of times I just want a simple Python 3 script that uses the standard library and can read arrow keys, so I do this:

    import sys, termios, tty
    
    key_Enter = 13
    key_Esc = 27
    key_Up = '\033[A'
    key_Dn = '\033[B'
    key_Rt = '\033[C'
    key_Lt = '\033[D'
    
    fdInput = sys.stdin.fileno()
    termAttr = termios.tcgetattr(0)
    
    def getch():
        tty.setraw(fdInput)
        ch = sys.stdin.buffer.raw.read(4).decode(sys.stdin.encoding)
        if len(ch) == 1:
            if ord(ch) < 32 or ord(ch) > 126:
                ch = ord(ch)
        elif ord(ch[0]) == 27:
            ch = '\033' + ch[1:]
        termios.tcsetattr(fdInput, termios.TCSADRAIN, termAttr)
        return ch
    

提交回复
热议问题