0

How to break only when KeyboardInterrupt is raised?

I have a something function that is not fully debugged that it can have a lot of random exceptions that I don't know about. But I want to ignore them except when I interrupt the process. Then I use a try...except... for it. For example

counter = 0
data = []
while True : 
    try : 
       data.append(something())
       counter+=1
    except : 
       continue

    if counter % 100 == 0 : 
       yield data
       data = []
yield data

How do I break it when I KeyboardInterrupt it?

  • 1
    "How do I break it when I KeyboardInterrupt it?" - it automatically stops, doesn't it ? – TheEagle Feb 02 '21 at 03:58
  • Hi! Can you please better the question and the example. The ` something` functions is not there, and please clarify what you use the `try...except...` for it would be great. Do you want the function to yield when the KeyboardInterrupt occurs or do you want the whole program to end - which would be happening already? What is it? – Rohan Asokan Feb 02 '21 at 03:58
  • @RohanAsokan I think he doesn't like the look of a stack trace when hitting ctrl-c. – Kris Feb 02 '21 at 04:03
  • Actually, no.. I'm confused too – Kris Feb 02 '21 at 04:04
  • Haha @Kris it **is** confusing. – Rohan Asokan Feb 02 '21 at 04:04
  • @IKnowHowBitcoinWorks I updated my answer, is that what you had in mind? – Kris Feb 02 '21 at 04:23
  • @Programmer it doesn't seems to be the case. it just keeps throwing errors untils the iteration is stopped. I added another try and except inside the something() and have the inner exception to print something then iterate 1000 times. It printed a lot of lines when I interrupt it. – IKnowHowBitcoinWorks Feb 02 '21 at 04:36

2 Answers2

0

You could collect exceptions and only show them to the user if a KeyboardInterrupt is raised, e.g.

from time import sleep
import random


def something():
    """ flip a coin to decide whether to throw an error """
    if random.choice((True, False)):
        raise ValueError('bla bla')
        

exceptions = []

for i in range(20):
    print('i:', i)
    
    try:
        something()
        sleep(1)
        
    except KeyboardInterrupt:
        print('interrupted')
        raise KeyboardInterrupt(repr(exceptions))
        
    except Exception as e:
        exceptions.append(e)

This will give a stack trace like:

KeyboardInterrupt: [ValueError('bla bla'), ValueError('bla bla'), ValueError('bla bla'), ValueError('bla bla'), ValueError('bla bla')]

Kris
  • 22,079
  • 3
  • 30
  • 35
0

You can do this if you only want to break on keyboardInterupt:-

counter = 0
data = []
while True : 
    try : 
       data.append(something())
       counter+=1
    except KeyboardInterrupt:
        break
    except:
        continue

    if counter % 100 == 0 : 
       yield data
       data = []
yield data

This will do the trick.