How do I abort the execution of a Python script? [duplicate]
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.
Solution 1:
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.
Solution 2:
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()