如何在linux中真正绑定python控制台程序中的键?

时间:2013-07-08 20:52:31

标签: python linux

我正在寻找python [linux]中的键绑定。

我的程序必须抓住键'q'并正确关闭。

我发现了这个

import curses
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

stdscr.addstr(0,10,"Hit 'q' to quit")
stdscr.refresh()

key = ''
while key != ord('q'):
    key = stdscr.getch()
    stdscr.addch(20,25,key)
    stdscr.refresh()
    if key == curses.KEY_UP: 
        stdscr.addstr(2, 20, "Up")
    elif key == curses.KEY_DOWN: 
        stdscr.addstr(3, 20, "Down")

curses.endwin()

但它卡住循环,当按下任何键时,我的程序必须每秒工作并在后台捕捉'q'。

1 个答案:

答案 0 :(得分:0)

添加:

stdscr.nodelay(True)

到程序的开头。然后getch会马上回来。如果用户上次调用getch后没有按任何东西,它将返回-1。