Python Exit Program

Learn how to exit a Python program or script using sys.exit(), exit(), quit(), return, and break, including exit codes, messages, functions, loops, and common mistakes.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python Exit Program

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.

python
import sys

print("Start")
sys.exit()
print("This will not run")
Output

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.

python
import sys

print("done")
sys.exit(0)
Output

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.

python
import sys

# success
sys.exit(0)
Output
python
import sys

# generic error
sys.exit(1)
Output

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).

python
import sys

sys.exit("Invalid input file")
Output

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.

python
def check_age(age):
    if age < 18:
        return "Not allowed"
    return "Allowed"


print(check_age(16))
print("still running")
Output

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:

python
import sys


def main():
    sys.exit("Stopping the program")


main()
Output

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.

python
for number in range(10):
    if number == 5:
        break
    print(number)
Output

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.

python
import sys

path = ""
if not path:
    sys.exit(1)
print("would load file")
Output

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.

python
import sys

try:
    sys.exit(3)
except SystemExit as e:
    print("caught", e.code)

print("still running because SystemExit was caught")
Output

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() or quit() in production scripts instead of sys.exit().
  • Thinking return ends the whole program—it only ends the function.
  • Thinking break ends the whole program—it only ends the loop.
  • Catching SystemExit (or a bare except:) 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 0 even when an error path runs—use non-zero codes for failures.
  • Using os._exit() in ordinary scripts; it terminates immediately without finally handlers or normal teardown, and is reserved for special cases like child processes after os.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.


References


Frequently Asked Questions

1. What is the best way to exit a Python script?

Use sys.exit() in scripts and CLIs; it raises SystemExit so finally blocks still run; avoid exit() and quit() outside the interactive interpreter.

2. What is the difference between return and sys.exit()?

return leaves the current function and hands control back to the caller; sys.exit() raises SystemExit and ends the interpreter unless that exception is handled.

3. What exit code should I use for success vs failure?

Use 0 (or omit the argument) for success; use a small non-zero integer such as 1 for a generic error—many shells and CI systems interpret non-zero as failure.

4. Does sys.exit() run finally blocks?

Yes—SystemExit inherits from BaseException and participates in normal exception unwinding, so finally clauses run; os._exit skips that cleanup.

5. Why should I not use exit() or quit() in production code?

They are injected by the site module for convenience in the REPL, are not the clearest contract for libraries, and style guides prefer sys.exit for real programs.
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …