如何防止Python密钥侦听器泄漏到下一个终端?

问题描述 投票:0回答:1

我在 Python 中有一个关键的监听器,可以从列表中选择一些选项。选择效果非常好。但是,我按下的任何键都将被键入下一个终端输入。例如,这是我的代码

import os
from pynput.keyboard import Key, Listener

cls = lambda:os.system("cls")

def on_press(key):
    """Listen for keywords like UP, DOWN and ENTER"""
    global KEY
    if key == Key.up:
        KEY = 'up'
        return False
    elif key == Key.down:
        KEY = 'down'
        return False
    elif key == Key.enter:
        KEY = 'enter'
        return False
    elif str(key) == "'\\x03'" or key == Key.esc:
        KEY = 'esc'
        return False
    return True

def OptionSelector(option: list) -> int:
    current = 0
    while True:
        output = ''
        cls()

        for text in option:
            index = option.index(text)
            output += '(*)' if current == index else '( )'
            output += f' {text}\n'
        print(output)

        with Listener(on_press=on_press) as OptionListener:
            OptionListener.join()

        global KEY
        if KEY == 'up':
            if current > 0:
                current -= 1
        elif KEY == 'down':
            if current != (len(option) - 1):
                current += 1
        elif KEY == 'enter':
            OptionListener.stop()
            cls()
            return current
        elif KEY == 'esc':
            exit()

print(OptionSelector(['a', 'b', 'c', 'd', 'e']))

当我按“abcdefg”时,我在 python 代码中看到的内容没有任何变化。但是,当我按下“Key.enter”时,代码将很好地执行,然后终端中的新行将显示我尝试在终端中执行

abcdefg

D:\codes\Python\data>abcdefg
'abcdefg' is not recognized as an internal or external command,
operable program or batch file.

D:\codes\Python\data>

如何阻止按键监听泄漏到下一个终端线路?

python keyboard pynput
1个回答
0
投票

使用

suppress
,停止输入。

替换此行:

with Listener(on_press=on_press) as OptionListener:

与:

with Listener(on_press=on_press, suppress=True) as OptionListener:

因此它会抑制所有键盘输入。小心这个!出现这种情况时,你只能依靠鼠标来停止程序。您可能想要添加一个故障保护,以便可以停止侦听器,因为 ctrl+c 将不再起作用。

© www.soinside.com 2019 - 2024. All rights reserved.