How To Terminate A Python Script

The easiest way to terminate a Python script is to raise a new SystemExit exception. When you raise a SystemExit exception somewhere in the program, it will terminate immediately and none of the code after it will execute.

 

Let's demonstrate this with a simple program, which will terminate halfway through.

 

print('hello')

raise SystemExit

print('hello again')
hello

An exception has occurred, use %tb to see the full traceback.

SystemExit

 

This is a nice solution since you don't need to import any extra Python packages.

 

If you don't like this syntax, import the sys package and use the sys.exit method to terminate the program.

 

import sys

print('hello')

sys.exit()

print('hello again')
hello
An exception has occurred, use %tb to see the full traceback.

SystemExit

 

Behind the scenes, sys.exit is calling raise SystemExit so there is no practical difference between using one method or another apart from syntax preference.