Use sys.exit() to stop a Python script or program. Use return to leave a function only. Use break to leave a loop only. Avoid exit() and quit() in production scripts—reserve them for the interactive shell. For exiting loops without stopping the interpreter, see Python break statement; for cleanup around failures, see Python try except.
The documentation for sys.exit describes it as raising SystemExit; because it is an exception, cleanup in finally blocks can still run before the interpreter shuts down. SystemExit is documented such that an integer argument becomes the process exit status, None means zero, and other objects (for example a string) are printed and the status is one.
import sys
print("Start")
sys.exit()
print("This will not run")You should see only Start. The second print never runs because sys.exit() ends the program (unless SystemExit is caught).
For calling conventions in general, see call a function from another file in Python. For timing a script that runs to completion without an early exit, see measure execution time.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
List of ways to exit (quick reference)
Prefer import sys and sys.exit(...) at process boundaries: main scripts, if __name__ == "__main__": blocks, and CLI entry points. It is explicit, works when the site module is disabled, and matches what linters and teams usually expect. When you parse arguments or print help before exiting, Python argparse pairs naturally with that pattern.
| Need | Use |
|---|---|
| Exit Python script | sys.exit() |
| Exit successfully | sys.exit(0) or sys.exit(None) |
| Exit with error | sys.exit(1) (or another non-zero int) |
| Exit with message | sys.exit("message") |
| Exit function only | return |
| Exit loop only | break |
| Skip one loop iteration | continue |
| Interactive shell | exit() or quit() |
| Avoid in normal scripts | os._exit() |
Exit a Python script using sys.exit()
sys.exit() raises SystemExit. The default argument is None, which ends with status 0. Any code after the call in the same scope will not run unless the exception is caught.
import sys
print("done")
sys.exit(0)You should see done only.
Exit with a status code
Use 0 (or None) for success and a non-zero integer for failure so shells and CI can detect errors.
import sys
# success
sys.exit(0)import sys
# generic error
sys.exit(1)Each snippet ends the interpreter in its own run; when you try them locally, run one block at a time. Conventionally 1 signals “something went wrong”; some programs use other small integers for specific errors.
Exit with an error message
Pass a string to print a message and exit with status 1 (unless you catch SystemExit yourself).
import sys
sys.exit("Invalid input file")You should see Invalid input file printed (typically to stderr) before the process stops.
exit() vs quit() vs sys.exit()
exit and quit are objects added by the site module for the interactive interpreter; calling them raises SystemExit, similar in effect to sys.exit(), but they are not meant as the primary API for installed scripts. The docs describe them as useful in interactive mode.
Use sys.exit() in files you ship. Use exit() or quit() in a REPL when you want a quick way to close the session—same idea, wrong tool for libraries and automation.
Exit a function using return
return hands a value back to the caller and resumes the rest of the program—it never terminates the whole process by itself.
def check_age(age):
if age < 18:
return "Not allowed"
return "Allowed"
print(check_age(16))
print("still running")You should see Not allowed then still running.
Do not write return exit() or return quit() to end a program from inside a function; that only returns the result of calling exit from the function and is confusing. To stop the whole program from main, call sys.exit() directly:
import sys
def main():
sys.exit("Stopping the program")
main()You should see Stopping the program and then the process ends.
Exit a loop using break
break leaves the innermost for or while loop; execution continues after the loop.
for number in range(10):
if number == 5:
break
print(number)You should see 0 through 4 on separate lines, not 5 or higher.
Exit a program when a condition is met
Combine a guard with sys.exit early in main or your top-level flow.
import sys
path = ""
if not path:
sys.exit(1)
print("would load file")You should see no would load line when path is empty—the process exits with code 1.
Handle SystemExit exception
You can catch SystemExit, but doing so by accident prevents shutdown. Libraries should almost never swallow it; applications might catch it at the very top to log and re-raise or convert to another policy.
import sys
try:
sys.exit(3)
except SystemExit as e:
print("caught", e.code)
print("still running because SystemExit was caught")You should see caught 3 then still running because SystemExit was caught. Without the except block, the process would end and that final print would not run.
try / finally still runs finally when sys.exit() fires, because SystemExit participates in normal unwinding—unlike os._exit, which skips finally and other cleanup.
When not to use exit() or quit()
Skip exit() and quit() in modules, packages, and scheduled jobs: they assume the site module has installed those names, and they read as “REPL convenience,” not a stable public API. Stick to sys.exit() for anything you would commit or deploy.
Common mistakes when exiting Python programs
- Using
exit()orquit()in production scripts instead ofsys.exit(). - Thinking
returnends the whole program—it only ends the function. - Thinking
breakends the whole program—it only ends the loop. - Catching
SystemExit(or a bareexcept:) unintentionally and keeping the interpreter alive. - Calling
sys.exit()deep inside reusable library functions where raising a normal exception would let callers decide how to stop. - Always exiting with
0even when an error path runs—use non-zero codes for failures. - Using
os._exit()in ordinary scripts; it terminates immediately withoutfinallyhandlers or normal teardown, and is reserved for special cases like child processes afteros.fork().
Summary
Use sys.exit with an optional integer status or string message to end a program in a controlled way while still allowing finally blocks to run. Use return inside functions and break inside loops when you only need to change local control flow. Treat exit() and quit() as interactive helpers, not replacements for sys.exit() in real scripts, and reserve os._exit() for rare low-level cases where you must bypass normal shutdown.

