1

I'm trying to program a kill sequence for a for loop, all the samples I see are for while loops, below is my code

I tried using the answer in here How to kill a while loop with a keystroke? using a while and my for inside the while, that allowed me to escape each for loop but it went on infinitely, and on its own as per the below fails too

results = []
try:
    for i in sites:
        do stuff for each site

except KeyboardInterrupt:
    print 'Keyboard Interrupt: script cancelled'
    import sys
    sys.exit()  

tried

try:
    while True:
        for i in sites:
AlexW
  • 2,843
  • 12
  • 74
  • 156

2 Answers2

0

Can you simplify your example to bare minimum which has the problem you are trying to solve? Your logic in general looks fine. Here's an example which will catch keyboard interrupt and continue:

import time

try:
    time.sleep(1000)
except KeyboardInterrupt:
    print('Caught keyboard interrupt.')

I think you have another problem in your code.

tayfun
  • 3,065
  • 1
  • 19
  • 23
  • I have simplified the above, I want to be able to cancel the whole for loop on a keyboard interrupt not a single instance – AlexW Jul 23 '17 at 14:21
  • Put a for loop in that try block and it won't work. It will get caught in the for loop and the Ctrl-C won't break. – user14241 Jan 19 '19 at 18:10
0

It is always hard for me to tell what loops python will or won't break from using Ctrl-C. This is a solution that has worked for me:

for i in sites:
    try:
        do stuff for each site
    except KeyboardInterrupt:
        print('\nKeyboard Interrupt: script cancelled')
        break

It's pretty simple, but it is difficult to find a straight answer to this question on stack overflow for some reason.

user14241
  • 727
  • 1
  • 8
  • 27