How to exit a Python script using sys.exit()?

Published on Aug. 22, 2023, 12:17 p.m.

To exit a Python script using sys.exit(), you can simply call the sys.exit() function with an optional exit code as an argument. Here’s an example:

import sys

# Do some stuff...

# Exit the script with a status code of 0
sys.exit(0)

In this example, we import the sys module and then do some work in the script. When we are ready to exit the script, we call sys.exit(0). The argument 0 is the exit status code, which indicates whether the script terminated successfully (exit code 0) or encountered an error (non-zero exit code).

You can also raise a SystemExit exception to achieve the same effect:

import sys

# Do some stuff...

# Exit the script with an error status code 
raise SystemExit(1)

In this example, we raise a SystemExit exception with an argument of 1, which is the exit status code indicating that the script encountered an error.

Note that sys.exit() and raise SystemExit() will both terminate the script immediately, so any code or functions after these statements will not be executed. It is generally recommended to use exceptions or return values instead of exiting immediately to allow for more graceful handling of errors.

Tags:

sys