I am aware of the die()
command in PHP which exits a script early.
How can I do this in Python?
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()
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.
Another way is:
raise SystemExit
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()