如何在输入时读取用户输入?

2024-09-26 18:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何让Python验证输入行并在输入时使用输入完成任务。 例如:

alphabet = "abcdefghijklmnopqrstuvwxyz"

useralphabet = input("Please enter however much of the alphabet you know:")

while(useralphabet in alphabet):
    break

print("You know", 26 - len(useralphabet), "letters of the alphabet!")

很明显,我知道这段代码无法按预期工作,但我希望它能说明我的想法,即让用户输入文本,直到他们输入的文本不再是指定字符串的一部分


Tags: ofthein文本youinputknowenter
2条回答

答案取决于您的操作系统。通常,操作系统只有在您按下ENTER键之后才将输入字符串交给python。如果需要按键入方式执行,则可能需要调用一些依赖于系统的调用来关闭输入缓冲

请参阅Python read a single character from the user了解有关此问题的更多信息

下面是一个工作示例(在Linux上使用Python 3.8.6进行测试)。如果需要为其他系统修改,请参阅this答案

hinput函数在输入字符时读取字符,并为通过新字符和整行的每个新字符调用on_char

在我的示例中,当用户键入xon_char函数返回True,这会导致hinput函数停止等待新输入

如果用户键入hello,它将自动完成为hello, world,并终止hinput

import sys
import termios
import tty
from typing import Callable

def main():
    hinput("prompt: ", on_char)
    return 0

def on_char(ch: str, line: str) -> bool:
    if ch == 'x':
        sys.stdout.write('\n')
        sys.stdout.flush()
        return True
    if line+ch == 'hello':
        sys.stdout.write("%s, world\n" % ch)
        sys.stdout.flush()
        return True
    return False

def hinput(prompt: str=None, hook: Callable[[str,str], bool]=None) -> str:
    """input with a hook for char-by-char processing."""
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    inpt = ""
    while True:
        sys.stdout.write('\r')
        if prompt is not None:
            sys.stdout.write(prompt)
        sys.stdout.write(inpt)
        sys.stdout.flush()
            
        ch = None
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)

        if hook is not None and hook(ch, inpt):
            break

        if ord(ch) == 0x7f: #BACKSPACE
            if len(inpt) > 0:
                sys.stdout.write('\b \b')
                inpt = inpt[:-1]
            continue

        if ord(ch) == 0x0d: #ENTER
            sys.stdout.write('\n')
            sys.stdout.flush()
            break

        if ch.isprintable():
            inpt += ch
            
    return inpt

if __name__ == '__main__':
    sys.exit(main())

相关问题 更多 >

    热门问题