Reputation: 1
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
Upvotes: 0
Views: 84
Reputation: 901
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.
Upvotes: 0