how to exit a python program code example

Example 1: python exit program

import sys
sys.exit()

Example 2: python exit program

#Exit everywhere with error message
import sys
sys.exit("Code not Pythonical")

#Exit with a specific status
import os
os._exit()

#Exit in interpreter
quit()

#Exit in Interpreter but more user friendly
exit()

Example 3: why doesn't sys.exit work?

import sys

try:
    sys.exit() # this always raises SystemExit
except SystemExit:
    print("sys.exit() worked as expected")
except:
    print("Something went horribly wrong") # some other exception got raised

Example 4: how to stop running code in python

#to stop all execution of code
exit()

Example 5: exit in python

import sys
msg = "bye bye"
sys.exit(msg)
# you can use it with out a msg

Tags:

Misc Example