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



我正在编写一个有无限循环的python脚本,为了停止,我使用常用的键盘中断键Ctrl+c,但我想知道程序停止后,我是否可以通过按空格来设置自己的类似键,我希望它具有与Ctrl+c[/em>相同的功能。因此,如果可能的话,我如何分配它

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

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

用于创建键盘侦听器(基于Jimmy Fraiture的回答和评论(,并在Space上使用exit()停止脚本(此处建议(

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()

相关内容

  • 没有找到相关文章

最新更新