How to read a single character from the user?

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

    An alternative method:

    import os
    import sys    
    import termios
    import fcntl
    
    def getch():
      fd = sys.stdin.fileno()
    
      oldterm = termios.tcgetattr(fd)
      newattr = termios.tcgetattr(fd)
      newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
      termios.tcsetattr(fd, termios.TCSANOW, newattr)
    
      oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
      fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    
      try:        
        while 1:            
          try:
            c = sys.stdin.read(1)
            break
          except IOError: pass
      finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
      return c
    

    From this blog post.

提交回复
热议问题