exit python program

Exit Python Program in 7 Different Ways!

Exiting a Python program is useful when your code is running in a loop or unresponsive. We are going to discuss different methods to exit python program.

If your Python programs encounter a situation that it can’t recover from, terminating the program is quite useful. There are different ways to exit from a program.

  1. Force exit
  2. Graceful exit

Force exit kills the process instantly and doesn’t bother about running clean-up code. Whereas in a graceful kill, it will run the clean-up code or finalizers that are registered to run at the end of the program.

A graceful exit is a preferred way to exit the program.

Quick Summary:

There are different ways to exit a running program in Python. Here is a quick summary of these –

  1. exit() and quit() – These functions are available in builtins module and raises SystemExit exception. Both can be used as synonymous. The only difference is, with quit(), we can print the message that the programming is terminating.
  2. sys.exit() – This function from sys module works similar to the exit() and quit() but allows you to run any clean-up codes before the program terminates.
  3. os._exit() from the os module terminates the program immediately, without giving any chance for a graceful exit, and doesn’t save any unsaved data.
  4. If you want to kill the python program from the command line, you can either use CTRL+C or kill the process directly.


sys.exit() is the preferred way to exit the python program in production-level code. This allows you to terminate the program with the exit code returned to the OS and also runs the necessary cleanup code before the program terminates.

Exit Python Program:

1. With exit() or quit()

Both quit() and exit() functions are synonymous and used to exit the Python program. These are built-in python functions and when called, they raise SystemExit exception which the interpreter catches and exits the program.

When we use exit() or quit(), the program exits immediately without running any clean-up code or finalizers.

The exit() method doesn”t take any arguments. Here is how the exit() method is implemented.

Here are the internal implementations of these methods.

def exit():

    #raises the SystemExit exception
    raise SystemExit(status)

Even the quit() method is implemented the same way. However, instead of raising the SystemExit exception, it calls the exit() method internally which invokes the SystemExit. However, it is not commonly used among Python programmers.

def quit():

    # quit method internally calls the exit

exit() and quit()

exit() and quit() are the popular and easy ways to exit the program immediately. However, these don’t call any finalizers defined in the program. So if you wanted to do some important operation before exiting the program, we can’t achieve it with these two methods.

Here is a sample example where you have to exit the program based on user input:

Let’s say, you are writing a python program to run a game in loop and if you wanted to exit the game when user presses the Esc button on the keyboard, here is the code for this.

from msvcrt import getch

def play_game():

    while True:
        if ord(getch()) == 27L
            print('Exiting the game')


2. Using sys.exit()

sys.exit() way of terminating the program is similar to that of exit() method. However, sys.exit([arg]) method allows you to run the clean up code and finalizers before the program ends.

It also takes an optional status code argument which can be used to define whether the program exited normally or is it a abnormal exit. The integer value 0 indicates a successful exit and any non-zero value will be treated as an abnormal exit of the program.

import sys

from msvcrt import getch

def play_game():

    while True:
        if ord(getch()) == 27L
            print('Exiting the game')


The sys.exit() method is preferrable way to exit the python program elegantly.

3. Use os._exit() method

Another simple way to exit a python program is by using os._exit() method. When this is called, the Python program will be terminated immediately without calling any clean-up code and flushing the buffer output. We can use this method if graceful termination is not required.

You need to import os module to use this method. It takes optional statuscode argument used to define whether the program exited normally or due to some other reason.

Here is the sample code for this.

import os


os._exit() method has to be used with caution since it doesn’t run any clean up code and flush the buffer data.

4. Directly Raise SystemExit

All the above-mentioned methods internally raise the SystemExit exception. So instead of using the exit() or quit() method, we can directly invoke the SystemExit exception from the python code.

Here is the code to exit python program by raising SystemExit exception

def perform_calculation():

       #some code that may raise an exception

    except Exception:
       print("Error occurred. Existing the program.")
       raise SystemExit(1)

if__name__ == "__main__":

5. KeyboardInterrupt exception

KeyboardInterrupt exception is raised when we press the CTRL+C keys while running the program. This will raise KeyboardInterrupt exception and we can catch it and use any clean up code.

main thread

KeyboardInterrupt exception is raised on the main thread of the program. If there are multiple threads in your program, write code to communicate this message based on a flag to all the threads.

6. Kill the process

An alternative way to kill any ongoing python program is by killing the process. kill is a linux command to send a signal to an on-going process, to kill it.

We need to pass the process id of the python program to this command.

kill -9 <PID>

You can find the process ID of the program by using the below command.

ps -ef | grep python

Be aware that, kill command causes the python program to terminate immediately and it will not perform graceful exit. Hence, there may be data loss or corruption with this method. It is not recommended to use this unless the Python program is not responding to other mentioned methods.

We can also use killall method to kill all the python processes with this command.

killall python

7. With Loop using break

Another way to exit the the program running in loop is by using a break statement. In the below example, if the certain condition is met, we can use break to exit the loop.

count = 0

while True:
   if(count == 100):

When graceful exit is helpful?

A graceful shutdown is generally preferred over a forceful exit for many reasons. It allows you a chance to run the clean-up code and finalizers before you exiting the program. Otherwise, all the resources used in that program will be undefined state.

  1. If you are working with the database or external resources, closing the HTTP and JDBC connections before exiting the program is recommended so that the connection pool is released and can be used by other programs.
  2. Similarly, if you are working with some file and you got an exception while performing some file operation, it is helpful to close or save the file before terminating.

In the above listed methods to exit Python program, sys.exit() method helps you to gracefully terminate the python program.

Follow codethreads.dev on for more insightful stories.

Frequently Asked Questions

  • How do I exit a Python program in the terminal?

    We can exit the python program from the terminal by using either the CTRL+C command or by killing the process. Detailed code with KeyboardInterrupt exception is explained here.

  • Difference between exit(0) and exit(1) in Python?

    exit() is a function in os module that is used to terminate python program immediately. It takes an integer argument that denotes whether it is a normal exit or an abnormal one.

    To know more about the status codes and their meanings, check out the above section.

  • How do you end the loop in Python?

    We can end a loop in Python using a break. Alternatively, you can also use different methods like exit() and quit() explained in this guide.

Leave a Comment

Your email address will not be published. Required fields are marked *