在 Python 中创建自定义键盘中断键

Creating a custom Keyboard Interrupt key in Python

几天前我发布了 但我没有得到确切的答案我得到的只是来自用户 Jimmy Fraiture

的一些无法解释的代码

这是他提供的代码:

from pynput.keyboard import Listener

def on_press(key):
    # check that it is the key you want and exit your script for example



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

# do your stuff here
while True:
    pass

我得到了代码,但我不知道如何使用它,如果我有一个 while 循环如何设置我的 space 键来打破它循环或成为键盘中断键请有人解释代码或提供答案我将不胜感激

这是您要找的吗?

import keyboard  # using module keyboard
from pynput.keyboard import Listener
    
    
def on_press(key):
    if keyboard.is_pressed("s"):  # if key 's' is pressed
        exit()
        


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

要使用 while 循环,您应该删除侦听器

import keyboard  # using module keyboard
from pynput.keyboard import Listener


while True:
    if keyboard.is_pressed("s"):  # if key 's' is pressed
        exit()