Appearance
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:
Terminate a script in Python by the sys.exit method
python
import sys
# Your script code goes here
# ...
sys.exit()
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
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:
Terminate a script with a specific code in Python by the sys.exit method
python
import sys
# Your script code goes here
# ...
sys.exit(0) # Script completed successfullyAlternatively, you can use the raise SystemExit statement to raise a SystemExit exception, which will have the same effect as using sys.exit().
Terminate a script in Python by raising a SystemExist exception
python
# Your script code goes here
# ...
raise SystemExitIt'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.
Terminate a script with a specific code in Python by the os._exit method
python
import os
os._exit(0)It should be used with caution, only if you need to terminate the process immediately.