3

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?

3
  • 1
    Inside the loop you'll need to check if a key has been pressed, and if so, get it and see if it's the one that stops the loop. Checking for keypresses is OS-depend, although there are some third-party modules that work on several platforms that can do that (and more). Commented Jul 21, 2021 at 19:31
  • 1
    Here's one of them named keyboard and another named pynput. Commented Jul 21, 2021 at 19:37
  • Ctrl+C is 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 and raise KeyboardInterrupt or use while running and set running = False Commented Jul 21, 2021 at 20:15

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

About "keyboard", these's an Erorr when you're not root: ImportError: You must be root to use this library on linux.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.