Python 检查是否按了箭头键或escape-非阻塞
我使用此代码检查用户是否按下了箭头键。它很好用。现在我还要检查一下是否按下了退出键。我假设如果不是箭头键,那一定是逃生键 在某种程度上是可行的,问题是箭头键包含3个字符,而转义键只有1个字符。这意味着您必须按Escape键多次才能得到响应Python 检查是否按了箭头键或escape-非阻塞,python,linux,python-3.x,stdin,Python,Linux,Python 3.x,Stdin,我使用此代码检查用户是否按下了箭头键。它很好用。现在我还要检查一下是否按下了退出键。我假设如果不是箭头键,那一定是逃生键 在某种程度上是可行的,问题是箭头键包含3个字符,而转义键只有1个字符。这意味着您必须按Escape键多次才能得到响应 import sys import select import tty import termios from time import sleep def is_key_pressed(): return select.select([sys.std
import sys
import select
import tty
import termios
from time import sleep
def is_key_pressed():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
def reset_terminal(old_settings):
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
while True:
if is_key_pressed():
char = ord(sys.stdin.read(1))
if char == 27:
ch = ord(sys.stdin.read(2)[1])
if ch in [65, 66, 67, 68]:
print("Arrow pressed")
continue
print("Escape pressed")
sleep(0.1)
finally:
reset_terminal(old_settings)
在打印“Escape pressed”之前,我尝试重置,但没有成功。正在打印Escape pressed,只是花了点时间。。。(看起来你的代码有点滞后)它正在打印,只是需要时间。。。(看起来您的代码中存在某种滞后)