How do I exit a script early, like the die()
command in PHP?

- 24,552
- 19
- 101
- 135

- 108,121
- 75
- 161
- 195
-
4simply use ```import os``` ```os._exit()``` – Amin Pial Jun 28 '21 at 00:42
-
xonsh: https://xon.sh/tutorial.html#that-s-all-folks – Andrew Oct 06 '22 at 16:02
14 Answers
import sys
sys.exit()
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 oftry
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.
-
19Presumably `sys.exit()` doesn't work (doesn't kill the process, just kills the thread) if raised by a background thread? – Feb 07 '11 at 19:53
-
2@cesium62: Yes, `sys.exit()` raises a `SystemExit` exception in the current thread. – Dmitry Trofimov Oct 23 '12 at 14:34
-
20Is there a way to end a script without raising an exception? I am already passing relevant flags out of the script with print to stdout piping into Popen, so the exception in this case is causing more trouble than it is solving. – Elliot Oct 01 '14 at 15:26
-
5Why, when I use this method do I get the following warning: ```UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)``` – Bill Oct 31 '16 at 18:11
-
1
-
@Bill http://stackoverflow.com/questions/25007104/what-the-error-when-i-close-the-dialog – Jan 29 '17 at 14:12
-
2If you're using `Tkinter` it will not stop the root process `mainLoop` and the window it displays. For this, you need the additional line of `root.destroy()`. – Roy Hinkley Jul 20 '17 at 17:17
-
-
but how do i terminate execution of the script and **automatically** trigger cleanup? – oldboy Dec 13 '21 at 09:40
-
If you structure your if statements correctly, you can often avoid the need for `sys.exit()`; the script will exit naturally when there's nothing else left to do. I guess the only time you'd need this is when something unfinished is taking longer that the user is willing to wait. – Lonnie Best Jan 10 '22 at 05:33
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()

- 158,662
- 42
- 215
- 303

- 5,159
- 3
- 16
- 15
-
127also sys.exit() will terminate all python scripts, but quit() only terminates the script which spawned it. – VishalDevgire Dec 03 '13 at 12:34
-
5Do you know if this command works differently in python 2 and python 3? – David C. Dec 27 '16 at 18:33
-
1Does anyone know if this will exit the whole interpreter, or just cause the script to stop executing? Speicifically: for a script running in Spyder, with the Python interpreter remain interactive, or will it be killed? Try to just stop the script from continuing, but leave interpreter interactivity present. – Demis Oct 15 '18 at 17:27
-
5
-
7I'm in python 3.7 and quit() stops the interpreter and closes the script. – RockAndRoleCoder Jan 15 '19 at 05:41
-
29According to the [documentation](https://docs.python.org/3/library/constants.html#quit) `quit()` is "*useful for the interactive interpreter shell and should not be used in programs*." – wovano Mar 25 '20 at 09:05
-
I'am using Python 3.7 with Jupyter Lab, and both Quit() and Exit() were solemnly ignored by my script. Any suggestions? – Ramon Feb 12 '21 at 14:00
-
`sys.exit()` will raise a `SystemExit` exception which, if left uncaught, will terminate the interpreter. It doesn't terminate the script immediately and it doesn't affect scripts that were started in a different python process. Since it's an exception, if called within a `try`-`except`-`finally` block, the `finally` block will still be executed. – scign Aug 14 '21 at 16:09
-
-
@s.paszko It works better than os.exit and sys.exit, IME, but I can't seem to get it to get it to break out of an input statement in the main thread from another thread. – Brōtsyorfuzthrāx Nov 30 '22 at 11:32
Another way is:
raise SystemExit

- 57,710
- 92
- 283
- 453

- 12,806
- 16
- 39
- 38
-
45@Alessa: it looks more elegant, but it's not recommended: you're directly raising a builtin exception instead of the preferable (and overwrittable) `sys.exit` wrapper – MestreLion May 04 '12 at 07:06
-
5This is a perfect way for me: Just quit the running script but not quit the IDLE – rml Mar 24 '18 at 04:26
You can also use simply exit()
.
Keep in mind that sys.exit()
, exit()
, quit()
, and os._exit(0)
kill the Python interpreter. Therefore, if it appears in a script called from another script by execfile()
, it stops execution of both scripts.
See "Stop execution of a script called with execfile" to avoid this.

- 1
- 1

- 1,027
- 8
- 3
-
5For me os._exit(0) was the most elegant way for me. All the others raised unwanted errors – Abdullah Ashraf Nov 02 '20 at 18:36
-
1Please do not use `quit()` or `exit()` in your code. These functions are intended only for the interactive Python. See [Python exit commands - why so many and when should each be used?](https://stackoverflow.com/a/19747562/320437) – pabouk - Ukraine stay strong May 11 '22 at 17:15
While you should generally prefer sys.exit
because it is more "friendly" to other code, all it actually does is raise an exception.
If you are sure that you need to exit a process immediately, and you might be inside of some exception handler which would catch SystemExit
, there is another function - os._exit
- which terminates immediately at the C level and does not perform any of the normal tear-down of the interpreter; for example, hooks registered with the "atexit" module are not executed.

- 31,152
- 11
- 87
- 129
-
1Used in AWS Glue Job, `os._exit()` is the only way to terminate the job properly without errors. – Jérémy Sep 22 '21 at 09:47
-
@Jérémy but is it a graceful shutdown? do you know if you can have hanging things after this? New to Python so ignore my lack of knowledge – bogdan.rusu Nov 03 '21 at 08:24
-
2@bogdan.rusu, `os._exit()` exits the entire process without any cleanup. Since in AWS the running VM instance will be discarded at the end of the job, this is not a problem for me. – Jérémy Nov 03 '21 at 10:56
I've just found out that when writing a multithreadded app, raise SystemExit
and sys.exit()
both kills only the running thread. On the other hand, os._exit()
exits the whole process. This was discussed in "Why does sys.exit() not exit when called inside a thread in Python?".
The example below has 2 threads. Kenny and Cartman. Cartman is supposed to live forever, but Kenny is called recursively and should die after 3 seconds. (recursive calling is not the best way, but I had other reasons)
If we also want Cartman to die when Kenny dies, Kenny should go away with os._exit
, otherwise, only Kenny will die and Cartman will live forever.
import threading
import time
import sys
import os
def kenny(num=0):
if num > 3:
# print("Kenny dies now...")
# raise SystemExit #Kenny will die, but Cartman will live forever
# sys.exit(1) #Same as above
print("Kenny dies and also kills Cartman!")
os._exit(1)
while True:
print("Kenny lives: {0}".format(num))
time.sleep(1)
num += 1
kenny(num)
def cartman():
i = 0
while True:
print("Cartman lives: {0}".format(i))
i += 1
time.sleep(1)
if __name__ == '__main__':
daemon_kenny = threading.Thread(name='kenny', target=kenny)
daemon_cartman = threading.Thread(name='cartman', target=cartman)
daemon_kenny.setDaemon(True)
daemon_cartman.setDaemon(True)
daemon_kenny.start()
daemon_cartman.start()
daemon_kenny.join()
daemon_cartman.join()

- 158,662
- 42
- 215
- 303

- 1,434
- 1
- 13
- 11
-
7This seem to be the only way to deal with obnoxiously deferred callbacks! (i.e. multi-threaded methods.) – not2qubit Oct 11 '18 at 19:45
-
5Well done. None of the other answers directly address multiple threads, only scripts spawning other scripts. – jonspaceharper Nov 07 '19 at 01:39
from sys import exit
exit()
As a parameter you can pass an exit code, which will be returned to OS. Default is 0.
-
3
-
13Just for posterity on the above comment - `exit()` and `sys.exit()` are not the same thing. Don't use the built-in `exit()` in scripts, this is just a helper for the interactive shell - use `sys.exit()` – daveruinseverything May 22 '19 at 23:30
I'm a total novice but surely this is cleaner and more controlled
def main():
try:
Answer = 1/0
print Answer
except:
print 'Program terminated'
return
print 'You wont see this'
if __name__ == '__main__':
main()
...
Program terminated
than
import sys
def main():
try:
Answer = 1/0
print Answer
except:
print 'Program terminated'
sys.exit()
print 'You wont see this'
if __name__ == '__main__':
main()
...
Program terminated Traceback (most recent call last): File "Z:\Directory\testdieprogram.py", line 12, in main() File "Z:\Directory\testdieprogram.py", line 8, in main sys.exit() SystemExit
Edit
The point being that the program ends smoothly and peacefully, rather than "I'VE STOPPED !!!!"

- 694
- 8
- 15
-
26One problem would be if you're in nested functions and just want to exit, you either have to send a flag all the way back up to the top function or you'll just return to the next level up. – horta Mar 30 '15 at 13:42
-
18This is an absolute nonsense if you're trying to suggest that you can use `return` to terminate the script. All the `return` is doing is returning a value and a flow of control to the calling function. There it continues with the execution right after the call of the function which called `return`. Of course, if the `return` is the last statement in your script as in your example, then the script is terminated right after it is called. – David Ferenczy Rogožan Jan 16 '17 at 22:24
-
4There's a strong argument to be made for this approach: (1) "exit" from the middle is arguably a "goto", hence a natural aversion; (2) "exit" in libraries are definitely bad practice (and _anything_ can become a library), since what a _library_ considers "unrecoverable" is usually fine to the _caller_. (Note: using exceptions for exits is a python practical work-around for C/C++/Java devs always inappropriately calling `exit` -- hence python programmers may not notice the stench of this code smell as much); and lastly, (3) multi-threaded code (which pythonistas have historically just ignored). – michael Dec 08 '17 at 04:02
-
2This is a philosophically different approach - OP is asking how to stop a script "early"; this answer is saying "don't": include a path to finish gracefully, return control to the `main` method and run to completion. I think this approach should be preferred when available. – scign Aug 14 '21 at 16:17
Problem
In my practice, there was even a case when it was necessary to kill an entire multiprocessor application from one of those processes.
The following functions work well if your application uses the only main process. But no one of the following functions didn't work in my case as the application had many other alive processes.
quit()
exit(0)
os._exit(0)
sys.exit(0)
os.kill(os.getppid(), 9)
- whereos.getppid()
is the pid of parent process
The last one killed the main process and itself but the rest processes were still alive.
Solution
I had to kill it by external command and finally found the solution using pkill
.
import os
# This can be called even in process worker and will kill
# whole application included correlated processes as well
os.system(f"pkill -f {os.path.basename(__file__)}")

- 5,029
- 3
- 12
- 34
-
2Your exact code didn't work for me, but you pointed me in the right direction: os.system("pkill -f " + sys.argv[0]) – Oriol Vilaseca Jul 27 '22 at 09:19
In Python 3.5, I tried to incorporate similar code without use of modules (e.g. sys, Biopy) other than what's built-in to stop the script and print an error message to my users. Here's my example:
## My example:
if "ATG" in my_DNA:
## <Do something & proceed...>
else:
print("Start codon is missing! Check your DNA sequence!")
exit() ## as most folks said above
Later on, I found it is more succinct to just throw an error:
## My example revised:
if "ATG" in my_DNA:
## <Do something & proceed...>
else:
raise ValueError("Start codon is missing! Check your DNA sequence!")

- 1,974
- 2
- 19
- 29
-
1I completely agree that it's better to raise an exception for any error that can be handled by the application. But the question was how to terminate a Python script, so this is not really a (new) answer to the question. – wovano Mar 25 '20 at 09:28
Just put at the end of your code quit()
and that should close a python script.

- 4,552
- 14
- 29
- 49

- 37
- 7
My two cents.
Python 3.8.1, Windows 10, 64-bit.
sys.exit()
does not work directly for me.
I have several nexted loops.
First I declare a boolean variable, which I call immediateExit
.
So, in the beginning of the program code I write:
immediateExit = False
Then, starting from the most inner (nested) loop exception, I write:
immediateExit = True
sys.exit('CSV file corrupted 0.')
Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:
if immediateExit:
sys.exit('CSV file corrupted 1.')
Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits.
'CSV file corrupted 1.5.'
In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.
And following the gradual sys.exit-ing from all the loops I manage to do it.
Full code: (some changes were needed because it is proprietory code for internal tasks):
immediateExit = False
start_date = '1994.01.01'
end_date = '1994.01.04'
resumedDate = end_date
end_date_in_working_days = False
while not end_date_in_working_days:
try:
end_day_position = working_days.index(end_date)
end_date_in_working_days = True
except ValueError: # try statement from end_date in workdays check
print(current_date_and_time())
end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
print('New end date: ', end_date, '\n')
continue
csv_filename = 'test.csv'
csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
try:
with open(csv_filename, 'r') as file:
print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
last_line = file.readlines()[-1]
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
resumedDate = start_date
if last_line == csv_headers:
pass
elif start_date not in working_days:
print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
immediateExit = True
sys.exit('CSV file corrupted 0.')
else:
start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
print('\nLast date:', start_date)
file.seek(0) # setting the cursor at the beginnning of the file
lines = file.readlines() # reading the file contents into a list
count = 0 # nr. of lines with last date
for line in lines: #cycling through the lines of the file
if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
count = count + 1
if immediateExit:
sys.exit('CSV file corrupted 1.')
for iter in range(count): # removing the lines with last date
lines.pop()
print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))
if immediateExit:
sys.exit('CSV file corrupted 1.2.')
with open(csv_filename, 'w') as file:
print('\nFile', csv_filename, 'open for writing')
file.writelines(lines)
print('\nRemoving', count, 'lines from', csv_filename)
fileExists = True
except:
if immediateExit:
sys.exit('CSV file corrupted 1.5.')
with open(csv_filename, 'w') as file:
file.write(csv_headers)
fileExists = False
if immediateExit:
sys.exit('CSV file corrupted 2.')

- 67
- 2
- 11
-
2Thanks for your contribution, but to me this answer makes no sense. Since you only post a few snippets of code instead of a complete example it's hard to understand what you mean. With only the lines of code you posted here the script would exit immediately. I can only guess that you have a try-catch block, which catches the SystemExit exception that is already mentioned in other answers. If you would rewrite your answer with a full working example of how you would *cleanly* exit an application (i.e. by performing some necessary shutdown actions) I think your post could be a useful addition. – wovano Mar 25 '20 at 09:21
-
Thank you for your feedback. Now I added the part of the code, which concerns the exit statements. – Matthew Mar 25 '20 at 12:41
-
Okay, this gives a bit more context :) Although now I think that your solution is actually a work-around for very bad programming patterns. First of all, you should never use `except:` without exception type. If you just use `except Exception:` (or even a more detailed exception type if possible), the `sys.exit()` would work as intended and you would not need this work-around. – wovano Mar 25 '20 at 15:28
-
Secondly, it seems like you try to do quite a number of things in one method, or probably even in the global file scope. It would help to break down your code in smaller pieces (functions), for example: (1) load input file, (2) process data, and (3) write output file. Then if step 1 would fail, you would skip steps 2 and 3. You could raise an exception anywhere during the loading step and you could handle the exception in one place. Using `sys.exit()` is really a sort of last-resort solution for critical errors. Just my two cents :) – wovano Mar 25 '20 at 15:29
-
In general, I do not see a global exit/halt functionality in Python, and I am forced to make it this way. The CSV file is really critical for me, so I guard it by all means possible, even if the means might look ugly. I am reading [The Hichhicker's Guide to Python](https://docs.python-guide.org/writing/style/) to improve my style. – Matthew Mar 25 '20 at 16:26
-
wovano, you are mentioning "very bad programming patterns". Where I can read about good programming patterns? Your answer would be highly appreciated. – Matthew Mar 25 '20 at 21:22
-
You mentioned the Hitchhiker's Guido to Python and I see that it mentions the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), for example. At least a number of rules of it are very applicable to this post, IMHO, although I can understand that it might require some experience to figure that out. There are lots of books about programming patterns, and by reading a lot on SO and other websites you will also learn a lot. You could also post your code on [Code Review](https://codereview.stackexchange.com/) and ask for feedback (note: only working code, it's not for debugging help). – wovano Mar 25 '20 at 21:52
use exit
and quit
in .py files
and sys.exit
for exe files