我在 Python 中遇到了键盘输入的问题。我尝试使用 raw_input,但它只调用一次。但我希望每次用户按下任何键时都能读取键盘输入。我该怎么做?谢谢回答。
我在 Python 中遇到了键盘输入的问题。我尝试使用 raw_input,但它只调用一次。但我希望每次用户按下任何键时都能读取键盘输入。我该怎么做?谢谢回答。
例如,您有一个像这样的Python代码:
#!/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()。
break
的无限 while
循环:In [11]: while True:
...: k = raw_input('> ')
...: if k == 'q':
...: break;
...: #do-something
> test
> q
In [12]:
getch
一样。(如果我记得getch
函数的话) - saulspatzgetch
函数 ;) - zhangxaochen
raw_input
确实会读取键盘输入,直到用户按下“Enter”键为止。你应该花些心思描述一下你想要实现什么。 - Nir Alfasi