我不知道任何跨平台的轻量级模块可以监听按键。但是,如果您想实现一些简单的操作,这里有个建议:
在Python常见问题解答中查看有关一次获得一次按键的问题。您可以尝试屏蔽来自
sys.stdin和的读取
threading。但这仅适用于Unix。在Windows上,您可以使用
msvcrt.kbhit。
结合Python FAQ和
msvcrt模块中的按键配方,结果
kbhit函数将如下所示:
try: from msvcrt import kbhitexcept 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)



