如何在Python中读取键盘输入

3

我在 Python 中遇到了键盘输入的问题。我尝试使用 raw_input,但它只调用一次。但我希望每次用户按下任何键时都能读取键盘输入。我该怎么做?谢谢回答。


1
你的问题不够清晰... raw_input 确实会读取键盘输入,直到用户按下“Enter”键为止。你应该花些心思描述一下你想要实现什么。 - Nir Alfasi
1
可能是https://dev59.com/PWct5IYBdhLWcg3wUb5-的重复问题。 - Azsgy
@saulspatz和Vaclav,请检查我的答案编辑。 - user4396006
1
@Václav Pavlíček 当你说“它不起作用”时,这并不是很有信息量的。具体是什么情况?顺便问一下,你是在使用Windows还是其他操作系统? - saulspatz
请重新检查我的答案。现在它肯定可以工作了。我刚在我的 Mac 上运行了它。 - user4396006
显示剩余5条评论
2个回答

10

例如,您有一个像这样的Python代码:

file1.py

#!/bin/python
... do some stuff...

在文档的某个特定点,您希望始终检查输入:

while True:
    input = raw_input(">>>")
    ... do something with the input...

这将永远等待输入。您可以将该无限循环作为单独的进程进行线程处理,同时执行其他任务,以便用户输入可以对您正在执行的任务产生影响。

如果您想仅在按下键时请求输入,并将其作为循环执行,则可以使用此代码(取自Steven D'Aprano的ActiveState配方)等待按键事件发生,然后请求输入、执行任务并返回到先前状态。

import sys

try:
    import tty, termios
except ImportError:
    # Probably Windows.
    try:
        import msvcrt
    except ImportError:
        # FIXME what to do on other platforms?
        # Just give up here.
        raise ImportError('getch not available')
    else:
        getch = msvcrt.getch
else:
    def getch():
        """getch() -> key character

        Read a single keypress from stdin and return the resulting character. 
        Nothing is echoed to the console. This call will block if a keypress 
        is not already available, but will not wait for Enter to be pressed. 

        If the pressed key was a modifier key, nothing will be detected; if
        it were a special function key, it may return the first character of
        of an escape sequence, leaving additional characters in the buffer.
        """
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
那么如何处理呢?现在,每次想要等待按键时,只需调用getch()即可。就像这样:
while True:
    getch() # this also returns the key pressed, if you want to store it
    input = raw_input("Enter input")
    do_whatever_with_it

你也可以将其线程化并在此期间执行其他任务。

请记住,Python 3.x 不再使用 raw_input,而是直接使用 input()。


3
Python 3确实很相关,因为这是一个开放的问答网站,不仅仅是原帖的人访问该页面。他们必须注意到内置方法只能在Python 2.x中使用。而且原帖的人也可以知道这一点。信息不会伤害任何人。 - user4396006
@VáclavPavlíček 没错,它告诉你错误来自哪一行?你能粘贴完整的错误信息吗? - user4396006
@VáclavPavlíček,你没有在终端运行代码吗? - Padraic Cunningham
3
请提供您参考代码的链接:http://code.activestate.com/recipes/577977-get-single-keypress/ - Padraic Cunningham
1
@PadraicCunningham 当然,我现在就做。 - user4396006
显示剩余8条评论

1
在Python 2.x中,只需使用带有条件 break 的无限 while 循环:
In [11]: while True:
    ...:     k = raw_input('> ')
    ...:     if k == 'q':
    ...:         break;
    ...:     #do-something


> test

> q

In [12]: 

6
我认为这并不符合原帖作者的意愿。你需要在每个键后按Enter键。我认为他想要截取单独的按键,就像C语言中的getch一样。(如果我记得getch函数的话) - saulspatz
@saulspatz 不确定,但我猜测 OP 还不知道 C 语言中的 getch 函数 ;) - zhangxaochen
我认为他也不知道,而且既然他试图用Python编写,即使他知道也没有什么用。我并不是在批评你,只是想帮助OP。 :-) - saulspatz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接