我不知道任何跨平台的轻量级模块可以监听按键。但是,如果您想实现一些简单的操作,这里有个建议:
在Python常见问题解答中查看有关一次获得一次按键的问题。您可以尝试屏蔽来自sys.stdin
和的读取threading
。但这仅适用于Unix。在Windows上,您可以使用msvcrt.kbhit
。
结合Python FAQ和msvcrt
模块中的按键配方,结果kbhit
函数将如下所示:
try:
from msvcrt import kbhit
except ImportError:
import termios, fcntl, sys, os
def kbhit():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANow, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while True:
try:
c = sys.stdin.read(1)
return True
except IOError:
return False
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)