Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查是否按了箭头键或escape-非阻塞_Python_Linux_Python 3.x_Stdin - Fatal编程技术网

Python 检查是否按了箭头键或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

我使用此代码检查用户是否按下了箭头键。它很好用。现在我还要检查一下是否按下了退出键。我假设如果不是箭头键,那一定是逃生键

在某种程度上是可行的,问题是箭头键包含3个字符,而转义键只有1个字符。这意味着您必须按Escape键多次才能得到响应

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,只是花了点时间。。。(看起来你的代码有点滞后)它正在打印,只是需要时间。。。(看起来您的代码中存在某种滞后)