我在Python中有键盘输入问题。我尝试了raw_input,它只被调用一次。但是我想读取每次用户按任何键时的键盘输入。我该怎么做呢?谢谢你的回答。
例如你有这样的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()。
在python2。x,只需使用条件break
:
while
循环In [11]: while True:
...: k = raw_input('> ')
...: if k == 'q':
...: break;
...: #do-something
> test
> q
In [12]: