I have a python program with nested for and while loops.
I already read here about using KeyboardInterrupt and here about using SIGINT.
I implemented a try-catch block inside each loop with a message and an action into the except. Indeed, I tried with an explicit exit via sys.exit()
, with a break
and with a raise
by throwing the exceptions in order to catch them in the outer loop.
All the solutions do not work and the Ctrl+c is only catched by the outer loop, the inner loops do not catch it i.e. even if I press many times Ctrl+c, a complete iteration of the inner for and multiple iterations of the while are executed before to break.
Example code
import signal
signal.signal(signal.SIGINT, signal.default_int_handler)
for i in range(0,M):
try:
# do something
for j in range(0,N):
try:
# do something
while(P > 0):
try:
P-=1
# do something
except KeyboardInterrupt:
print("while loop exiting via Ctrl+c")
sys.exit(1) # break or raise
except KeyboardInterrupt:
print("inner foor loop exiting via Ctrl+c")
sys.exit(1) # break or raise
except KeyboardInterrupt:
print("outer for loop exiting via Ctrl+c")
sys.exit(1) # break or raise
Do you have any suggestion?
Edit: I forgot to say that while loop is inside a function called by the inner for loop. I do not think that this is a problem.