0

while the script is running, it needs to be outside the input to catch the keyword and break the loop, I need to break the loop instantly with the 'esc' word, while the script waits for input by the user

¿how do i that?

import time ; import keyboard as kb

while (True):
    if kb.is_pressed('esc'):
        break
    n = str(input('f(x) = '))
    print(n)
    time.sleep(1)

its a bit whim but the only way to stop the loop is to hold the 'esc' keyword and it would be more comfortable to press the key and instantly break the loop, i tried a few methods but they all lead to the same thing and this one is the most efficient

  • 1
    Maybe remove the `sleep`, `input` already slows loop execution. – 101 Feb 04 '23 at 05:16
  • 1
    Does this answer your question? [How to stop an infinite loop safely in Python?](https://stackoverflow.com/questions/32922909/how-to-stop-an-infinite-loop-safely-in-python) – Ishwor Khatiwada Feb 04 '23 at 05:40
  • If you don’t mind changing the key, you’ll find that Ctrl+C will stop the loop immediately. – nneonneo Feb 04 '23 at 06:08

1 Answers1

0

If you are fine with using Ctrl+C instead of esc, you can just catch the KeyboardInterrupt error.

import time

while True:
    try: 
        n = str(input('f(x) = '))
        time.sleep(1)
    except KeyboardInterrupt:
            print("\nBreaking from the infinite loop")
            break

SIGINT is the signal sent when we press Ctrl+C. The default action is to terminate the process. However in Python, a KeyboardInterrupt error is raised.

It can be difficult to trigger a SIGINT when the escape key is pressed, since the interrupt process is hardware and OS dependent.

Shail
  • 881
  • 9
  • 20
  • 37