Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens exactly internally when I terminate my Python script using Ctrl+c?

These days I am learning Python's Exception handling features deeply. I encountered exception SystemExit. While reading about this from official Python Docs I got question in mind that what exactly would have happen when I terminate Python script by pressing Ctrl+c?

lets take this sample code:

def func1(a,b):
    print "func1: "+str(a/b)
    #some more functions

def func2(a,b):
    print "func2: "+str(a/b)
    #some more functions

if __name__=="__main__":
    import random

    count=0
    for i in range(1000000):
            count=count+1
            print "count: "+str(count)
            try:
                    func1(random.randint(-2,3),random.randint(-2,3))
            except KeyboardInterrupt:
                    raise
            except:
                    print "error in func1"
            try:
                    func2(random.randint(-2,3),random.randint(-2,3))
            except KeyboardInterrupt:
                    raise
            except:
                    print "error in func2"

            print "\n"

In this sample code I am catching KeyboardInterrupt so I can stop my script by pressing Ctrl+c. Should I catch SystemExit too to make this code more mature? if yes then why? actually this question is source of my main question which appear on title. so don't consider that I am asking two different question in one post.

like image 401
Alok Avatar asked Mar 21 '23 18:03

Alok


1 Answers

You usually not need to catch SystemExit as it is what makes exit() and sys.exit() functions work:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

Example:

try:
    exit()
except SystemExit:
    print "caught"

Therefore, you usually don't want to catch all exceptions in the first place (by using an empty except: clause). The best approach is generally to make your exception handlers as specific as possible. It otherwise makes debugging your application exceptionally hard, as it either hides errors entirely or at least makes it hard to diagnose the details.

like image 66
moooeeeep Avatar answered Mar 23 '23 06:03

moooeeeep