sys.exit() will do exactly what you want.

import sys
sys.exit("Error message")
Answer from Moses Schwartz on Stack Overflow
Top answer
1 of 14
1856
import sys
sys.exit()

This will exit with status code 0; if you don't want that, you can pass a different one or a message:

sys.exit(1)

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

Note that this is the 'nice' way to exit. @glyphtwistedmatrix below points out that if you want a 'hard exit', you can use os._exit(*errorcode*), though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

2 of 14
529

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()

However, this relies on an implicit import of the site module. Per the docs:

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.

As such, if the -S flag is passed, this may raise a NameError with the message "name 'quit' is not defined".

Discussions

Terminate code
Your program will terminate normally when you reach the end. You just have to make sure it reaches the end. Without seeing what you're doing, it's hard to give advice. More on reddit.com
🌐 r/learnpython
25
19
September 21, 2023
execution - How to stop/terminate a python script from running? - Stack Overflow
I wrote a program in IDLE to tokenize text files and it starts to tokeniza 349 text files! How can I stop it? How can I stop a running Python program? More on stackoverflow.com
🌐 stackoverflow.com
Is there a way to immediately stop a python script with a keystroke?
🌐 r/learnpython
14
0
November 3, 2023
Debugging a python script with arguments in bash
https://github.com/bulletmark/debugpy-run More on reddit.com
🌐 r/vscode
3
0
January 17, 2022
🌐
LearnPython.com
learnpython.com › blog › end-python-script
How Do You End Scripts in Python? | LearnPython.com
Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.
🌐
Scaler
scaler.com › home › topics › how to end program in python
How to End Program in Python - Scaler Topics
March 21, 2024 - Explanation: In the above code, we terminated our Python program by using the os._exit() command. One of the approaches to ending the program successfully in Python is through handling the uncaught exceptions. It is uncommon to build a script that works flawlessly on the first try; it typically requires multiple revisions.
🌐
Tutor Python
tutorpython.com › end-a-program-in-python
Here is how to end a Program in Python - Tutor Python
October 21, 2024 - The sys.exit() function is one of the most common ways to terminate a Python program. It raises the SystemExit exception, which can be caught in the code if needed, but generally, it effectively terminates the program.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Ending a Python Script Gracefully - Raspberry Pi Forums
November 19, 2021 - try: while True: # Main code goes here except KeyboardInterrupt: print( "Exit." ) That seems to work beautifully. Many thanks Another trick is to put a Carriage Return in front of the "Exit." message:
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-exit-a-python-script
How to Exit a Python script? - GeeksforGeeks
December 7, 2023 - There exist several ways of exiting Python script applications, and the following article provides detailed explanations of several such approaches How to exit Python script. In this example, we will see How to Use the exit() Function in Python. ...
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › python-exit-how-to-use-an-exit-function-in-python-to-stop-a-program
Python Exit – How to Use an Exit Function in Python to Stop a Program
June 5, 2023 - By Shittu Olumide The exit() function in Python is used to exit or terminate the current running script or program. You can use it to stop the execution of the program at any point.
🌐
Codecademy
codecademy.com › article › python-exit-commands-quit-exit-sys-exit-os-exit-and-keyboard-shortcuts
Python Exit Commands: quit(), exit(), sys.exit(), os._exit() and Keyboard Shortcuts | Codecademy
The quit() command in Python is often used to stop execution while working in the interpreter. It offers a quick and readable way to end an interactive session, such as when testing code snippets in the REPL (Read–Eval–Print Loop).
🌐
Replit
replit.com › home › discover › how to end a program in python
How to end a program in Python | Replit
February 6, 2026 - It's crucial to properly end a Python program for clean code and resource management. Functions like sys.exit() and quit() offer controlled ways to terminate scripts effectively.
🌐
HashBangCode
hashbangcode.com › article › stopping-code-execution-python
Stopping Code Execution In Python | #! code
After this you can then call the exit() method to stop the program running. It is the most reliable, cross-platform way of stopping code execution. Here is a simple example. ... You can also pass a string to the exit() method to get Python to ...
🌐
Altcademy
altcademy.com › blog › how-to-end-program-in-python
How to end program in Python - Altcademy.com
August 31, 2023 - Every program you start must have an endpoint, a moment when it stops executing. This is what we call program termination. In Python, a program naturally terminates when Python interpreter has executed all the lines of code.
🌐
DataCamp
datacamp.com › tutorial › how-to-exit-python-a-quick-tutorial
How to Exit Python: A Quick Tutorial | DataCamp
April 5, 2024 - 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.
🌐
Quora
quora.com › Is-there-any-way-to-close-a-python-script-without-using-the-exit-command
Is there any way to close a python script without using the 'exit()' command? - Quora
Answer (1 of 4): exit() is not a “command.” It’s the invocation of a function (specifically one of Python’s builtin functions). Also exit() is far more the most common way to terminate the execution session of a Python script. The most common way for a Python script to “close” is by simply allow...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-exit-commands-quit-exit-sys-exit-and-os-_exit
Python exit commands: quit(), exit(), sys.exit() and os._exit() - GeeksforGeeks
July 12, 2025 - Example: In the given code, the sys.exit("Age less than 18") line will terminate the Python script with a message "Age less than 18" if the variable age is less than 18. If age is 18 or greater, it will print "Age is not less than 18".
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to terminate a script in python?
How to terminate a script in Python? - Spark By {Examples}
May 31, 2024 - The exit() function takes a single optional argument, which is the exit status code. If no argument is provided, the exit status code defaults to 0, which indicates the successful termination of the script.
🌐
Edureka Community
edureka.co › home › community › categories › python › how to exit a python script in an if statement
how to exit a python script in an if statement | Edureka Community
September 19, 2018 - I'm using Python 3.2 and trying to exit it after the user inputs that they don't want to continue, ... (), sys.quit(), quit(), and raise SystemExit.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › python exit commands
Python Exit Commands | Interview Kickstart
November 7, 2024 - Python exit commands explained: sys.exit(), quit(), Ctrl+D, and best practices for graceful program termination in scripts and REPL.