4
votes

For a simple python script that doesn't start any threads or fork any processes, what's the difference between simply letting execution reach the end of the script and explicitly calling quit(), exit(), or sys.exit()?

i.e. what's the difference between

def main():
    # do some stuff
    print("Done doing stuff")

if __name__ == '__main__':
    main()

and

import sys

def main():
    # do some stuff
    print("Done doing stuff")
    # explicit exit
    sys.exit()

if __name__ == '__main__':
    main()

I'm asking this because I have been having some odd garbage collection issues on script termination (exceptions raised from __del__ apparently due to the order in which things get cleaned up) without the explicit exit() call, and adding an explicit exit() appears to correct those issues. Or at least none of those exceptions get printed after calling exit(), maybe they are simply being silenced.

1
From what I garner, the sys.exit() allows the 'finally' clause, wherein the clean-up functionality is built, of some try blocks to activate by raising an exception, thereby giving a "cleaner" exit.Uvar
docs.python.org/3/library/sys.html#sys.exit "This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored". Another interesting note is the one on the buffering errors caught while cleaning up, which cause the exit code to become 120BoboDarph
I believe this should answer your questions: stackoverflow.com/questions/19747371/…Brandon C
So if I really want to exit properly, I have to catch all exceptions, manually print a stack trace, and then call sys.exit()?alex.forencich

1 Answers

0
votes

In the case you have posted, there is no difference. But the are cases in which you may want to terminate your program without waiting for it to finish.

A banal example:

try:
    ...
except KeyboardInterrupt:
    x = input('Sure you want to exit? y/n')
    if x == 'y':
        quit()
    else:
        pass