How to terminate a Python script

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to terminate a Python script and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to terminate a Python script, which can be followed any time. Take easy to follow this discuss.

How to terminate a Python script

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?

Asked By: Teifion


Answer #1:

import sys

details from the sys module documentation:


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

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.

Answered By: pjz

Answer #2:

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.


#do stuff
if this == that:
Answered By: j.m.g.r

Answer #3:

Another way is:

raise SystemExit
Answered By: Vhaerun

Answer #4:

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.

Answered By: Space cowboy

Answer #5:

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.

Answered By: Glyph

Answer #6:

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!")
    while True:
        print("Kenny lives: {0}".format(num))
        num += 1
def cartman():
    i = 0
    while True:
        print("Cartman lives: {0}".format(i))
        i += 1
if __name__ == '__main__':
    daemon_kenny = threading.Thread(name='kenny', target=kenny)
    daemon_cartman = threading.Thread(name='cartman', target=cartman)
Answered By: eaydin

Answer #7:

from sys import exit

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.

Answered By: cleg

Answer #8:

I’m a total novice but surely this is cleaner and more controlled

def main():
        Answer = 1/0
        print  Answer
        print 'Program terminated'
    print 'You wont see this'
if __name__ == '__main__':

Program terminated


import sys
def main():
        Answer = 1/0
        print  Answer
        print 'Program terminated'
    print 'You wont see this'
if __name__ == '__main__':

Program terminated Traceback (most recent call last): File “”, line 12, in
main() File “”, line 8, in main
sys.exit() SystemExit


The point being that the program ends smoothly and peacefully, rather than “I’VE STOPPED !!!!”

Answered By: Floggedhorse

Leave a Reply

Your email address will not be published. Required fields are marked *