How To Exit Python Script

Exiting a Python script may seem like a simple task, but it is a critical skill for any developer.

Knowing how to properly exit a script can save you valuable time and ensure that your code operates efficiently. In this tutorial, we will go through the necessary steps to successfully exit a Python script.


1. Use the exit() Function

The simplest way to exit a Python script is to use the exit() function. This function terminates the program and returns an exit status code to the shell.

Here is an example:

2. Use the sys.exit() Function

Another way to exit a Python script is to use the sys.exit() function. This function is similar to exit(), but it provides more control over the exit status code. The exit code can be any integer value, but 0 usually indicates successful termination.

Here is an example:

3. Use a try/except Block

If you need to handle exceptions before exiting your Python script, you can use a try/except block. This will allow you to catch any exceptions that occur and gracefully exit the program.

Here is an example:


Exiting a Python script is essential for any developer. Whether you use the exit() or sys.exit() function or a try/except block, make sure that your code exits gracefully and returns an appropriate exit status code.