如何将 "KeyboardInterrupt" 命令替换为另一个键?
How to replace the "KeyboardInterrupt" command for another key?
我有以下代码:
while True:
try:
#DoSomething
except KeyboardInterrupt:
break
但我不想使用 Crtl + C,而是想键入另一个键来结束循环。我该怎么做?
这是一个使用我在第二条评论中提到的 keyboard
模块的简单示例。它处理我在第一条评论中提到的大部分步骤,并可在多个平台上运行。当用户按下 Ctrl + B 键时,循环将停止。
请注意 Ctrl + C 仍会引发 KeyboardInterrupt
。
import keyboard
from time import sleep
def callback(keyname):
global stopped
print(f'{keyname} was pressed!')
stopped = True
keyboard.add_hotkey('ctrl+b', lambda: callback('Ctrl-B'))
stopped = False
print('Doing something...')
while not stopped:
sleep(1) # Something
print('-fini-')
您可以使用 keyboard
模块:
import keyboard
while True:
if keyboard.is_pressed("some key"):
break
do_something()
这将一直执行某些操作,直到按下 some key
。然后,它就会跳出死循环。
要捕获热键,请使用 add_hotkey
函数:
import keyboard
def handle_keypress(key):
global running
running = False
print(key + " was pressed!")
running = True
keyboard.add_hotkey("ctrl+e", lambda: handle_keypress("Ctrl-E"))
while running:
do_something()
或者您可以使用 pynput
:
from pynput.keyboard import Listener
def on_press(key):
print('{0} pressed'.format(
key))
with Listener(
on_press=on_press) as listener:
listener.join()
我有以下代码:
while True:
try:
#DoSomething
except KeyboardInterrupt:
break
但我不想使用 Crtl + C,而是想键入另一个键来结束循环。我该怎么做?
这是一个使用我在第二条评论中提到的 keyboard
模块的简单示例。它处理我在第一条评论中提到的大部分步骤,并可在多个平台上运行。当用户按下 Ctrl + B 键时,循环将停止。
请注意 Ctrl + C 仍会引发 KeyboardInterrupt
。
import keyboard
from time import sleep
def callback(keyname):
global stopped
print(f'{keyname} was pressed!')
stopped = True
keyboard.add_hotkey('ctrl+b', lambda: callback('Ctrl-B'))
stopped = False
print('Doing something...')
while not stopped:
sleep(1) # Something
print('-fini-')
您可以使用 keyboard
模块:
import keyboard
while True:
if keyboard.is_pressed("some key"):
break
do_something()
这将一直执行某些操作,直到按下 some key
。然后,它就会跳出死循环。
要捕获热键,请使用 add_hotkey
函数:
import keyboard
def handle_keypress(key):
global running
running = False
print(key + " was pressed!")
running = True
keyboard.add_hotkey("ctrl+e", lambda: handle_keypress("Ctrl-E"))
while running:
do_something()
或者您可以使用 pynput
:
from pynput.keyboard import Listener
def on_press(key):
print('{0} pressed'.format(
key))
with Listener(
on_press=on_press) as listener:
listener.join()