0

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.

erotavlas
  • 512
  • 6
  • 18
  • 2
    I added a few sleeps in your code to slow it down and I was able to break the inner loop. Maybe you have a timing problem? – toti08 Aug 07 '18 at 07:38
  • @toti08 I do not think so. The outer for loop only prints information while the inner for loop prepares the execution by fetching some information from the Web and from file and setups some classes. Finally, the while loop is where the execution lasts long. – erotavlas Aug 07 '18 at 07:47
  • Well, I guess your example is then not really suitable for your situation, as I was able to break it in the inner loop. You should try to make a more representative example, otherwise it's difficult to help you out here. – toti08 Aug 07 '18 at 07:49
  • I found this example https://gist.github.com/camilin87/8571791 and it works well. However, it does not stop gracefully... – erotavlas Aug 14 '18 at 15:16

0 Answers0