How to Exit a Python Script with an Error Message Using sys.exit
When a script can't go on, such as when a settings file is missing, the kindest thing is to stop with one clear sentence, not a traceback. Passing that sentence to sys.exit() does exactly that: Python prints it and ends the script with exit code 1, so the shell knows it failed. This guide shows it in zsh and PowerShell, with real output from Python 3.15.2.
Syntax
import sys
sys.exit(<message>)
| Part | What it means |
|---|---|
import sys | Loads the module that holds exit() |
<message> | A string. Python prints it to standard error and exits with code 1 |
Python's sys documentation: if the argument isn't an integer or None, "any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs."
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
import sys
settings_found = False
if not settings_found:
sys.exit("Can't find settings.toml. Create it, then run again.")
print("Starting")

settings_found stands in for a real check, such as whether a file exists.
Step 2: Run It and Read the Exit Code
- macOS / Linux
- Windows (PowerShell)
uv run python exit_message.py; echo $?
uv run python exit_message.py; $LASTEXITCODE
Can't find settings.toml. Create it, then run again.
1

The message printed without a traceback, Starting never printed, and the exit code was 1. Both shells gave the same output. Any program that runs the script, such as a CI job, sees the failure.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using print() for the message and then sys.exit(1) | It works, but the message goes to standard output, mixed with normal output | Pass the message to sys.exit() so it goes to standard error |
Calling exit() or quit() in a script | They're meant for the interactive prompt | Use sys.exit() in scripts |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The script stops but the exit code is 0 | It reached its end, or called sys.exit() with no argument | Pass a message or a nonzero number |
A bare except: around the code swallows the exit | sys.exit() raises SystemExit, which a bare except: catches | Catch specific exceptions instead |
FAQ
Where does the message go?
To standard error. In a terminal you see it like any other line; when output is redirected to a file, it stays on screen.
How is this different from sys.exit(1)?
sys.exit(1) exits with code 1 but prints nothing. Passing a string does both.
Conclusion
sys.exit("Can't find settings.toml. Create it, then run again.") printed the sentence, skipped the rest of the script and ended it with exit code 1, as echo $? and $LASTEXITCODE showed.
Additional Resources
- sys.exit — exit codes and messages.
