In PHP, we use die() to stop a script. What’s the equivalent in Python to exit a script mid-way or based on a condition? I’m looking for the proper way to python exit script without raising errors unnecessarily.
In my scripts, I typically use sys.exit(), it’s the most straightforward way to exit in Python without throwing a stack trace.
Just import sys at the top and call sys.exit() when needed.
You can even pass a message or status code:
python
Copy
Edit
import sys
if something_went_wrong:
print("Stopping script early.")
sys.exit()
It’s been my go-to for CLI tools or early termination in automation scripts.
If my script is function-based and structured properly, I often just use return to exit early.
For example:
python
Copy
Edit
def main():
if not valid:
print("Invalid input")
return
# rest of the script
main()
This keeps things clean without needing sys.exit() unless I really need to signal an error code.
@MiroslavRalevic For small, interactive scripts or Jupyter notebooks, I just use exit(), it’s built-in and works fine.
But I avoid it in real applications since it’s not meant for production use.
Under the hood, exit() and quit() just raise SystemExit, which is what sys.exit() does too, so you’re essentially doing the same thing, but sys.exit() is more explicit and reliable in all contexts.