How to read a single character from the user?

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

    My solution for python3, not depending on any pip packages.

    # precondition: import tty, sys
    def query_yes_no(question, default=True):
        """
        Ask the user a yes/no question.
        Returns immediately upon reading one-char answer.
        Accepts multiple language characters for yes/no.
        """
        if not sys.stdin.isatty():
            return default
        if default:
            prompt = "[Y/n]?"
            other_answers = "n"
        else:
            prompt = "[y/N]?"
            other_answers = "yjosiá"
    
        print(question,prompt,flush= True,end=" ")
        oldttysettings = tty.tcgetattr(sys.stdin.fileno())
        try:
            tty.setraw(sys.stdin.fileno())
            return not sys.stdin.read(1).lower() in other_answers
        except:
            return default
        finally:
            tty.tcsetattr(sys.stdin.fileno(), tty.TCSADRAIN , oldttysettings)
            sys.stdout.write("\r\n")
            tty.tcdrain(sys.stdin.fileno())
    

提交回复
热议问题