0
0
PythonHow-ToBeginner · 3 min read

How to Use sys.exit() in Python: Simple Guide

In Python, you use sys.exit() to stop your program immediately. Import the sys module first, then call sys.exit() with an optional exit status code to indicate success or failure.
📐

Syntax

The basic syntax to stop a Python program using sys.exit() is:

  • import sys: This imports the sys module which contains the exit function.
  • sys.exit([status]): This stops the program. The optional status can be an integer or string to indicate the exit reason.
python
import sys

sys.exit([status])
💻

Example

This example shows how to use sys.exit() to stop a program with a message and exit code.

python
import sys

print("Program started")

if True:
    print("Exiting program now.")
    sys.exit(0)  # 0 means success

print("This line will not run.")
Output
Program started Exiting program now.
⚠️

Common Pitfalls

Common mistakes when using sys.exit() include:

  • Forgetting to import sys before calling sys.exit().
  • Using sys.exit() inside threads without handling exceptions, which may not stop the whole program.
  • Expecting code after sys.exit() to run; it will not.
python
# Wrong: forgetting to import sys
# sys.exit(1)  # This will cause a NameError

# Correct usage:
import sys
sys.exit(1)
📊

Quick Reference

FunctionDescription
sys.exit()Exit program with status 0 (success)
sys.exit(0)Exit program with status 0 (success)
sys.exit(1)Exit program with status 1 (error)
sys.exit('message')Exit and print message to stderr

Key Takeaways

Always import sys before using sys.exit().
Use sys.exit() to stop your program immediately with an optional status code.
Code after sys.exit() will not run.
Passing 0 means success; non-zero means error.
sys.exit() can accept a string message to display on exit.