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.


Asked by: Chloe145 | Posted: 28-01-2022






Answer 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.

Answered by: Owen696 | Posted: 01-03-2022



Answer 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()

Answered by: Jared503 | Posted: 01-03-2022



Answer 3

import sys
sys.exit()

Answered by: Melanie470 | Posted: 01-03-2022



Answer 4

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: Carina249 | Posted: 01-03-2022



Answer 5

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: Emily662 | Posted: 01-03-2022



Answer 6

exit() should do the trick

Answered by: Walter379 | Posted: 01-03-2022



Answer 7

exit() should do it.

Answered by: Kelsey893 | Posted: 01-03-2022



Answer 8

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

Answered by: Andrew404 | Posted: 01-03-2022



Similar questions

syntax - Python code not following line of execution

Ignore the parameters and functions names. I have tested all the functions and they are individually fine. In the following code even after success has been printed the code in the #non-mutating section of the else part is being executed. Also despite having errors the loop is not terminating. def move(ar,x,y,xi,yi): #move(array,x,y,x-incr...


syntax - Python code not following line of execution

Ignore the parameters and functions names. I have tested all the functions and they are individually fine. In the following code even after success has been printed the code in the #non-mutating section of the else part is being executed. Also despite having errors the loop is not terminating. def move(ar,x,y,xi,yi): #move(array,x,y,x-incr...


bash - Execution of a OS command from a Python daemon

I've got a daemon.py with a callback. How should I make the handler function execute a OS command?


python - Execution of script using Popen fails

I need to execute a script in the background through a service. The service kicks off the script using Popen. p = Popen('/path/to/script/script.py', shell=True) Why doesn't the following script work when I include the file writes in the for loop? #!/usr/bin/python import os import time def run(): fd = open('/home/dilleyjrr/testOutput.txt', 'w') fd.write('...


Python | How to make local variable global, after script execution

Here is the code. What I need to do is find a way to make i global so that upon repeated executions the value of i will increment by 1 instead of being reset to 0 everytime. The code in main is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java. from __future__ import nested_scopes import sys import tim...


java - How can I measure the execution time of a for loop?

I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it? I know these platforms so i am talking about these: for (i = 0; i < 1000000; i++) { } I don't want to measure anything within the loop. Little bit modification: @all Some of the friends of mine are saying co...


runlevel - Python execution

Is it possible for a python script to execute at a low run level? Edit: To clarify, is it possible for a python script to run in the background, kind of like a daemon.


python - Cancel query execution in pyscopg2

How would one go about cancelling execution of a query statement using pyscopg2 (the python Postgres driver)? As an example, let's say I have the following code: import psycopg2 cnx_string = "something_appropriate" conn = psycopg2.connect(cnx_string) cur = conn.cursor() cur.execute("long_running_query") Then I want to cancel the execution of that long running query from another th...


c++ - Where does execution resume following an exception?

In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?


python - How to make Fabric execution follow the env.hosts list order?

I have the following fabfile.py: from fabric.api import env, run host1 = '192.168.200.181' host2 = '192.168.200.182' host3 = '192.168.200.183' env.hosts = [host1, host2, host3] def df_h(): run("df -h | grep sda3") And I get the following output: [192.168.200.181] run: df -h | grep sda3 [192.168.200.181] out: /dev/sda3 365G 180G 185G 50% /usr/local/nwe ...


Python order of execution

I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code. For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it is implemented before all the ones below it. Is it the same for Python? Like if I open a file of dat...


python - plotting lines without blocking execution

I am using matplotlib to draw charts and graphs. When I plot the chart using the command show() my code blocks at this command. I would like to refresh my list of values with new data , and than refresh the image on the background. How to do that without closing each time the window with the graph? Below is the code I am using import pylab a = (1,2,3,4) pylab.plot(a) pylab.show(...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top