DEV Community

Avnish
Avnish

Posted on

How to Exit a Python Program in the Terminal

Exiting a Python program gracefully is a fundamental aspect of Python programming, especially when running scripts in a terminal or interactive session. Whether you're developing on Windows, macOS, or Unix-based systems, understanding how to terminate your Python session properly can save time and ensure your scripts end as intended. Here's a concise guide on how to do so using various methods:

Running Python in the Terminal

Before we dive into exiting a Python program, let's briefly touch on how to run Python in the terminal:

  • Open your terminal or command prompt.
  • Type python (or python3 on some Unix-based systems if both Python 2 and Python 3 are installed) and press Enter.
  • You should see the Python interactive shell, indicated by the >>> prompt, where you can start typing Python code directly.

Exiting a Python Program

1. Using exit() and quit() Functions

Both exit() and quit() functions are built into the Python interpreter and are intended for use in the interactive shell. They allow you to exit from the Python session.

Example:

>>> print("Running some Python code")
Running some Python code
>>> exit()
Enter fullscreen mode Exit fullscreen mode

Or you can use:

>>> print("Running some Python code")
Running some Python code
>>> quit()
Enter fullscreen mode Exit fullscreen mode

After executing exit() or quit(), you'll return to your system's command line.

2. Using the Ctrl + Z Command in Windows

In a Windows terminal, you can use the Ctrl + Z command to send an EOF (End-Of-File) signal to the Python interpreter, which exits the current interactive session.

Steps:

  • Run your Python code as needed.
  • Press Ctrl + Z then Enter to exit the session.

3. Using the Ctrl + D Command in macOS/Linux

On macOS and other Unix-based systems, Ctrl + D serves a similar purpose to Ctrl + Z on Windows, sending an EOF signal to exit the interactive Python session.

Steps:

  • Run your Python code as needed.
  • Press Ctrl + D to exit the session.

Summary

  • Interactive Shell Exit: Use exit() or quit() functions within the Python interactive shell to terminate the session.
  • Windows Exit: Use Ctrl + Z then Enter in a command prompt to exit a Python interactive session.
  • macOS/Linux Exit: Use Ctrl + D in a terminal to send an EOF signal, exiting the Python interactive session.

By knowing these methods, you can ensure a smooth and controlled exit from your Python programs in various environments, enhancing your development workflow.

Top comments (0)