How do I terminate a script?

In Python, you can terminate a script by using the exit() function from the sys module. This function raises a SystemExit exception, which when uncaught causes the interpreter to exit. Here's an example of how you can use the exit() function to terminate a script:

import sys

# Your script code goes here
# ...

sys.exit()

Watch a course Python - The Practical Guide

You can also use the exit() function with a return code, which can be used to indicate the status of the script's execution to the system. For example:

import sys

# Your script code goes here
# ...

sys.exit(0) # Script completed successfully

Alternatively, you can use the raise SystemExit statement to raise a SystemExit exception, which will have the same effect as using sys.exit().

# Your script code goes here
# ...

raise SystemExit

It's also worth mentioning that you could use the os._exit() function. It immediately stops the program execution, and doesn't call any cleanup handlers, flush stdio buffers or call atexit-registered functions.

import os
os._exit(0)

It should be used with caution, only if you need to terminate the process immediately.