How To Exit Python Script/Program?

Python scripts or programs run forever unless the execution reaches the end or explicitly the script or program is exit explicitly. Python provides different ways and methods to quit from script or program. The sys.exit() is the standard and most popular way to exit from Python script/program. Also, the quit() method can be used too.

sys.exit() Method

The sys.exit() method is the best way and the most popular way to exit from a Python script/program. This is provided by the sys module . So in orde to use it the sys module should be imported. The ssy.exit() method also accepts parameters which can be an integer. This parameter is returned by the Python program/script in order to provide information about it. If the returned integer is 0 this means “succesfull termination” which means the script/program is executed and terminaed succesfully without an error or problem.

import sys

print("Some output")

#Exit or Terminate successfully
sys.exit(0)

Alternatively unsuccesfull termination message can be send by providing non-zero parameter to the sys.exit() method.

import sys

print("Some output")

#Exit or Terminate unsuccessfully
sys.exit(5)

exit() Method

The exit() method is also a built-in method in order to quit from the Python script/program. The exit() method is very similar to the built-in quit() method.

print("Some output")

exit()

Built-in quit() Method

The quit() method is a built-in method. It is provided by the Python interpreter default. There is no need to import any module. Just calling the quit() exits from the Python program/script. Under the hood, the quit() method raises the SystemExit exception.

print("Some output")

quit()

Raise SystemExit Exception

The most inconvenient way to exit from Python program or script is raising the SystemExit exception. This way raise an exception which means the termination is not succesful and there it an exception.

print("Some output")

raise SystemExit

os._exit(0) Method

The os._exit() method is a low-level method that exits the current Python program/script with specified status information without cleanup handlers, flushing stdio buffers, writing dirty data to the storage, etc. This is a bit inconvenient way which does not process regular termination procedure. The os._exit() method also accept parameter in order to provide exit code. the os._exit() method is mainly designed to exit from the child process or threads where the parent process and thread continue executing. As expected the os module should be imported to call the os._exit() method.

import os

print("I am child process")

os._exit(0)

Leave a Comment