Pynput键盘侦听器在一段时间后停止将键盘事件发送到程序

时间:2019-09-15 02:42:02

标签: python macos python-multithreading keyboard-events pynput

我正在使用pynput来侦听我在macOS上运行的程序中来自键盘按下/释放的事件

LOGGER_ACTION = {
    frozenset([Key.shift, Key.cmd, KeyCode(char='1')]): start_log,
    frozenset([Key.shift, Key.cmd, KeyCode(char='2')]): stop_log,
    frozenset([Key.shift, Key.cmd, Key.esc]): exit_log,
}

# Currently pressed keys
current_keys = set()


def on_press(key):
    current_keys.add(key)
    LOGGER_ACTION.get(frozenset(current_keys), lambda: None)()  
    # return False to stop listener


def on_release(key):
    if key in current_keys:
        current_keys.remove(key)

我在其他地方启动监听器

listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

当我运行python程序时,该程序会按预期接收键盘事件(在我的LOGGER_ACTION中执行适当的功能),但是一段时间后,我注意到侦听器已退出并且我的键盘操作未中继到该程序。为什么监听会在一段时间后停止?

完整代码在这里:https://github.com/nishanthprakash/StatisticalStoic/blob/master/src/productivity/timelogger.py

0 个答案:

没有答案
相关问题