是否可以在 Python 中创建自定义键盘中断键?

Is it possible to create a custom Keyboard Interrupt key in Python?

我正在编写一个 python 脚本,它有一个无限循环,为了停止我使用常用​​的键盘中断键 Ctrl+c 但我想知道是否可以在程序停止后按 space 来设置自己的一个我想让它和Ctrl+c一样的功能 那么,如果可能的话,我该如何分配呢?

您可以添加一个侦听器来检查您的按键何时被按下,然后停止您的脚本

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

用于创建键盘监听器(), and on Space stop the script using exit() (Suggested here)

from pynput.keyboard import Listener

def on_press(key):
    # If Space was pressed (not pressed and released), stop the execution altogether 
    if (key == Key.space):
        print('Stopping...')
        exit()

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


while True:
    print('Just doing my own thing...\n')
from pynput.keyboard import Listener
     while True:
         if keyboard.is_pressed("space"):
             exit()