How can I stop a Python script execution mid-way?

Is it possible to stop the execution of a Python script at any point with a command?

For example:

some code

quit()  # stop execution at this point

some more code (which will not be executed)

How can I achieve this in Python?

I’ve had a few instances where I needed to stop a Python script mid-way, and I found that using sys.exit() works perfectly. It halts the script and optionally lets you print a message before stopping. Example:

import sys
sys.exit("Error message")

This is a clean way to forcefully exit the script. You could consider using this if you want a controlled shutdown of your python stop process.

That’s a good point, @mark-mazay! Another simple way to stop a Python script is by using exit(). It’s a built-in function that works similarly, especially for stopping your script at certain points. You can even use it without an argument, but if you want to display a message, just like you did with sys.exit(), you can do:

exit("Stopping execution")

It’s an easy approach, and both methods — sys.exit() and exit() — are very useful when you want to perform a python stop gracefully.

Great additions, guys! Another option I’ve found useful, especially when I want to handle specific conditions, is raising a SystemExit. It works similarly to sys.exit(), but it gives more flexibility in error handling or custom exit scenarios. Example:

raise SystemExit("Execution stopped")

It also has the advantage of being catchable if you need to manage how you stop the Python script. So, in essence, there’s a range of ways to implement a python stop depending on how much control or handling you need over the exit process.