I have a Python script containing multiple loops, and when I execute it, it continues running indefinitely until I manually stop it (usually by interrupting the kernel in Jupyter). Although I generally don't need to stop it, there are times when I do. To simplify, let's consider the following code:
while True:
print("hello")
countdown(2)
print("hello2")
countdown(2)
print("hello3")
#if F2 has been pressed, yield and error to stop the script
I would like to achieve the following behavior in my Python script: If I press F2 while the print("hello") part is executing, the script should stop after printing print("hello3"). Similarly, if I press F2 while the print("hello2") part is executing, the script should also stop after printing print("hello3"). Essentially, I want the code to halt at the designated point, regardless of where I press F2. Additionally, I don't want the script to prompt me for input at each loop iteration, asking whether to stop the script or not. This is because I typically don't need to interrupt it in that manner.
I have no idea how to implement it