为什么转义键会延迟Python的诅咒? [英] Why does the escape key have a delay in Python curses?

查看:97
本文介绍了为什么转义键会延迟Python的诅咒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python curses模块中,我观察到在按下 esc 键和getch()返回之间存在大约1秒钟的延迟.对于其他键,似乎不会发生此延迟.为什么会发生这种情况,我该怎么办?

测试用例:

import curses
import time

def get_delay(window, key):
    while True:
        start = time.time()
        ch = window.getch()
        end = time.time()
        if ch == key:
            return end-start

def main(stdscr):
    stdscr.clear()
    stdscr.nodelay(1)

    stdscr.addstr("Press ESC")
    esc_delay = get_delay(stdscr, 27)

    stdscr.addstr("\nPress SPACE")
    space_delay = get_delay(stdscr, ord(' '))

    return esc_delay, space_delay

if __name__ == '__main__':
    esc_delay, space_delay = curses.wrapper(main)
    print("Escape delay: {} ms".format(esc_delay*1000))
    print("Space delay: {} ms".format(space_delay*1000))

结果:

Escape delay: 1001.09195709 ms
Space delay: 0.00596046447754 ms

解决方案

要自定义Esc延迟,您可以设置环境变量ESCDELAY,curses使用该变量确定释放Escape Key之前等待的时间(以毫秒为单位). /p>

为了在Python中定义此变量,您可以例如在调用curses.wrapper(main)之前先调用以下函数:

def set_shorter_esc_delay_in_os():
    os.environ.setdefault('ESCDELAY', '25')

如果以前没有设置过,它将把环境变量设置为25ms.

另请参见 ncurses手册页(搜索ESCDELAY).

>

In the Python curses module, I have observed that there is a roughly 1-second delay between pressing the esc key and getch() returning. This delay does not seem to occur for other keys. Why does this happen and what can I do about it?

Test case:

import curses
import time

def get_delay(window, key):
    while True:
        start = time.time()
        ch = window.getch()
        end = time.time()
        if ch == key:
            return end-start

def main(stdscr):
    stdscr.clear()
    stdscr.nodelay(1)

    stdscr.addstr("Press ESC")
    esc_delay = get_delay(stdscr, 27)

    stdscr.addstr("\nPress SPACE")
    space_delay = get_delay(stdscr, ord(' '))

    return esc_delay, space_delay

if __name__ == '__main__':
    esc_delay, space_delay = curses.wrapper(main)
    print("Escape delay: {} ms".format(esc_delay*1000))
    print("Space delay: {} ms".format(space_delay*1000))

Results:

Escape delay: 1001.09195709 ms
Space delay: 0.00596046447754 ms

解决方案

In order to customize the Esc delay you can set the environment variable ESCDELAY which curses uses to determine the time in milliseconds it waits before it delivers the Escape Key.

In order to define this variable in Python you could for example call the following function prior to your call to curses.wrapper(main):

def set_shorter_esc_delay_in_os():
    os.environ.setdefault('ESCDELAY', '25')

which will set the environment variable to 25ms if it has not been set before.

See also the man page of ncurses (search for ESCDELAY).

这篇关于为什么转义键会延迟Python的诅咒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆