例如,有一个Python代码如下:
文件1.py#!/bin/python
... do some stuff...
在文档的某一点上,您要始终检查输入:while True:
input = raw_input(">>>")
... do something with the input...
这将永远等待输入。您可以将这个无限循环作为一个单独的进程进行线程处理,同时执行其他操作,这样用户输入就可以在您正在执行的任务中产生效果。
如果您只想在按下某个键时请求输入,并将其作为循环执行,那么使用此代码(取自this ActiveState recipe by Steven D'Aprano),您可以等待按键发生,然后请求输入,执行任务并返回到上一个状态。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
你也可以线程,并在同一时间做其他的任务。
请记住,Python3.x不再使用原始输入,而只使用input()。