I have the following code:
while True:
try:
#DoSomething
except KeyboardInterrupt:
break
But instead of using Crtl + C, I want to type another key to end the loop. How can I do this?
You can use the keyboard module:
import keyboard
while True:
if keyboard.is_pressed("some key"):
break
do_something()
This will keep doing something until some key is pressed. Then, it will break out of the endless loop.
To catch hotkeys, use the add_hotkey function:
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()
Or you can use 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()
Here's a simple example of using that keyboard module I mentioned in my second comment. It handles most of steps I mentioned in my first comment and works on several platforms. The loop will stop if and when the user presses the Ctrl + B key.
Note that Ctrl + C will still raise a 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-')
keyboardand another namedpynput.Ctrl+Cis standard method to stop script in system and it is processed by system - for other keys you have to use some module to check pressed keys andraise KeyboardInterruptor usewhile runningand setrunning = False