How do I abort the execution of a Python script?

Question:

I have a simple Python script that I want to stop executing if a condition is met.

For example:

done = True
if done:
    # quit/stop/exit
else:
    # do other stuff

Essentially, I am looking for something that behaves equivalently to the ‘return’ keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.

Asked By: Ray

||

Answers:

exit() should do the trick

Answered By: Sec

exit() should do it.

Answered By: Dana

If the entire program should stop use sys.exit() otherwise just use an empty return.

Answered By: André
import sys
sys.exit()
Answered By: gimel

You could put the body of your script into a function and then you could return from that function.

def main():
  done = True
  if done:
    return
    # quit/stop/exit
  else:
    # do other stuff

if __name__ == "__main__":
  #Run as main program
  main()
Answered By: David Locke

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints “aa! errors!” and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn’t do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn’t normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

Answered By: ryan_s

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I’ve lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Answered By: efotinis

Try

sys.exit("message")

It is like the perl

die("message")

if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function

Answered By: GabrieleV
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.