Skip to main content
HomeTutorialsPython

How to Exit Python: A Quick Tutorial

In this article, we cover the basics of what happens when you terminate Python, how to exit Python using different exit functions and keyboard shortcuts, as well as common issues and how to avoid them.
Apr 2024

Often, when I am done working in Python, I simply use the close button in the corner of the IDE to terminate the program and the IDE handles terminating Python. However, there are times when I need to exit Python more programmatically, for instance when I’m working directly in the terminal or when I want a program to close Python automatically after running. In those cases, Python’s built-in exit functions are the way to go.

The Short Answer: Here’s How You Can Exit a Program in Python

Use exit() or quit() to terminate Python processes in casual code and sys.exit() in production code. Only use os._exit() in rare situations where you do not require cleanup tasks to be completed. Here are examples of exit(), quit(), and sys.exit() used in action:

Exiting Python with the exit() or quit() functions

print("Hello World! Let's exit the program")
exit() # Use the exit() function to terminate processes in casual code
print("Welcome back World!") # this code will not run after exiting
print("Hello World! Let's exit the program")
quit() # Use the quit() function to terminate processes in casual code
print("Welcome back World!") # this code will not run after quitting

Exiting Python with the sys.exit() function

import sys # In some cases, you may need to import the sys module
print("Hello World! Let's exit the program")
sys.exit() # Use the sys.exit() function to terminate processes in production code
print("Welcome back World!") # this code will not run after exiting

What Does Exiting Python Entail?

Exiting Python refers to the process of terminating the Python interpreter or session, effectively ending the Python program's execution. Usually, this involves executing cleanup tasks before terminating the interpreter and Python itself. Depending on how you exit Python, these cleanup processes will happen automatically, behind the scenes. You can learn more about the nitty-gritty of how this works in this software engineering principles course.

Four Methods to Exit Python Code

There are several methods for exiting Python, beyond that provided by your IDE. Let’s take a look at a few below:

Using the exit() or quit() functions

The exit() function can be used to raise a SystemExit exception, which terminates the Python interpreter. This is primarily useful in the interactive interpreter shell. It accepts an optional exit code argument, which is typically used to indicate the reason for exiting but may also be left empty.

exit()

or

exit(0)  # Exit with a success status

The quit() function works in the same way as the exit() function.

quit()

These two functions were added primarily to find a way out of the Python terminal easily. If you didn’t know how to close it, you would start typing “exit” or “quit” as reasonable guesses for how to escape.

Both the exit() function and the quit() function relies on the site module, which may not always be available. So, it is unwise to use this in production code.

Using the sys.exit() function for production code

In production code, it is common practice to use the sys.exit() function from the sys module to exit Python without relying on the site module. The sys module is generally available but you will need to import it. This function also accepts an optional exit code argument.

Similarly to exit() and quit(), sys.exit() raises a SystemExit exception that terminates Python.

import sys # In some cases, you may need to import the sys module
sys.exit()

Exit Python quickly with os._exit()

In addition to the exit() and quit() functions, Python offers the os._exit() function for quick termination with reduced functionality. Unlike exit() and quit(), which raises a SystemExit exception and then performs a few cleanup tasks. os._exit() terminates the Python process immediately without calling additional cleanup steps. To learn more about cleanup processes, read about exceptions and error handling in Python, or check out this Python for Developers course on Datacamp.

This function is useful when immediate termination is required, such as when the interpreter must shut down abruptly. But use caution; it bypasses the Python runtime's normal cleanup process which can cause problems down the road. In the vast majority of cases using exit(), quit(), or sys.exit() is a better option.

Keyboard shortcuts to exit Python

In the Python interpreter or terminal, you can exit Python by pressing Ctrl + Z on Windows or Ctrl + D on macOS. These shortcuts signal the interpreter that the file is complete and tell it to terminate Python. Like os._exit(), this method does not execute any cleanup tasks. If you want to use this method, you will want to ensure the appropriate cleanup tasks are explicitly addressed in your code.

Common Issues

The most important thing to consider when exiting a program is the cleanup tasks. Failing to complete the cleanup can cause problems with memory leakage, data loss or corruption, and a whole host of other problems. If your program starts behaving oddly, check to make sure you are properly running cleanup tasks during your exits.

Another common issue when exiting Python is inadvertently terminating the wrong session or interpreter, especially in environments with multiple active sessions. Be cautious when using keyboard shortcuts or exit functions to ensure you exit the intended session.

Other times, you may be working on a system that does not have the site module installed, which will render exit() and quit() useless. If this is the case, be sure to use sys.exit(), as the sys module will always be installed.

Conclusion

Exiting Python programmatically is an important aspect of Python programming. By understanding the various methods for exiting Python and their practical applications, you can effectively manage the execution and termination of Python code.

Learn more about using Python interpreters in this Python setup guide or this article on Python scripts. Learn how to use Python Shell in this Introduction to Shell Course or this Data Processing in Shell course. If you’re interested in becoming a Python programmer, check out DataCamp’s Python Programmer Career Track.


Photo of Amberle McKee
Author
Amberle McKee

I am a PhD with 13 years of experience working with data in a biological research environment. I create software in several programming languages including Python, MATLAB, and R. I am passionate about sharing my love of learning with the world.

Topics

Continue Your Python Journey Today!

Track

Python Programming

24hrs hr
Improve your Python programming skills. Learn how to optimize code, write functions and unit tests, and use software engineering best practices.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

cheat sheet

LaTeX Cheat Sheet

Learn everything you need to know about LaTeX in this convenient cheat sheet!
Richie Cotton's photo

Richie Cotton

tutorial

How to Convert a List to a String in Python

Learn how to convert a list to a string in Python in this quick tutorial.
Adel Nehme's photo

Adel Nehme

tutorial

A Comprehensive Tutorial on Optical Character Recognition (OCR) in Python With Pytesseract

Master the fundamentals of optical character recognition in OCR with PyTesseract and OpenCV.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Encapsulation in Python Object-Oriented Programming: A Comprehensive Guide

Learn the fundamentals of implementing encapsulation in Python object-oriented programming.
Bex Tuychiev's photo

Bex Tuychiev

11 min

tutorial

Python KeyError Exceptions and How to Fix Them

Learn key techniques such as exception handling and error prevention to handle the KeyError exception in Python effectively.
Javier Canales Luna's photo

Javier Canales Luna

6 min

code-along

Full Stack Data Engineering with Python

In this session, you'll see a full data workflow using some LIGO gravitational wave data (no physics knowledge required). You'll see how to work with HDF5 files, clean and analyze time series data, and visualize the results.
Blenda Guedes's photo

Blenda Guedes

See MoreSee More