3

I have a piece of code which is not in a function, say

x = 5
y = 10
if x > 5:
    print("stopping")

What can I put after the print statement to stop the code from running further? Sys.exit() works, but raises an error that I don't want in the program. I want it to quietly stop the code as if it had reached the end of the main loop. Thanks.

2
  • 2
    Python always raise SystemError on exit. You are probably catching everything in an except block. And you shouldn't do that Commented Apr 28, 2013 at 2:37
  • @JBernardo: Good point. You mean SystemExit, though. :) Commented Apr 28, 2013 at 3:14

5 Answers 5

12

As JBernardo pointed out, sys.exit() raises an exception. This exception is SystemExit. When it is not handled by the user code, the interpreter exits cleanly (a debugger debugging the program can catch it and keep control of the program, thanks to this mechanism, for instance)—as opposed to os._exit(), which is an unconditional abortion of the program.

This exception is not caught by except Exception:, because SystemExit does not inherit from Exception. However, it is caught by a naked except: clause.

So, if your program sees an exception, you may want to catch fewer exceptions by using except Exception: instead of except:. That said, catching all exceptions is discouraged, because this might hide real problems, so avoid it if you can, by making the except clause (if any) more specific.

My understanding of why this SystemExit exception mechanism is useful is that the user code goes through any finally clause after a sys.exit() found in an except clause: files can be closed cleanly, etc.; then the interpreter catches any SystemExit that was not caught by the user and exits for good (a debugger would instead catch it so as to keep the interpreter running and obtain information about the program that exited).

Sign up to request clarification or add additional context in comments.

6 Comments

I don't know! seriously! maybe the same person that down voted my answer.
Thank you! very informative. The intricacies of this have boggled my mind for some time, so it's nice to have a fresh view on it.
Is exit() same as os._exit()?
@jurgenreza, if you are referring to sys.exit(), then, no, they are different, as explained in the answer.
@EOL No i am referring to exit().
|
6

You can do what you're looking for by doing this:

import os
os._exit(1)

6 Comments

This function is bad and you shouldn't be using it
why did you suggest os._exit and not sys.exit? stackoverflow.com/questions/9591350/…
@Paul: He asked for a way to exit without raising an exception. Python will always raise an exception when using sys.exit. I agree that this isn't the way things should be done, but that's the answer to this question.
@CaptainSkyhawk: The reason why os._exit() causes problem is that it bypasses finally clean-up clauses. For instance, with os._exit(), a debugger would stop debugging the program because it loses control of it. That said, your answer is an answer to the question. I would only recommend it as a last resort, though, since it unconditionally makes the interpreter stop.
This function is not "bad": it's not deprecated, it doesn't, when used correctly, do any damage, and it's a deliberately exposed part of the API. It is the right function to use in various, very limited circumstances. sys.exit() is nearly always the correct answer though, as it is here.
|
2

sys.exit() which is equivalent to sys.exit(0) means exit with success. sys.exit(1) or sys.exit("Some message") means exit with failure. Both cases raise a SystemExit exception. In fact when your program exists normally it is exactly like sys.exit(0) has been called.

Comments

0

When I ran across this thread, I was looking for a way to exit the program without an error, without an exception, have the code show as 'PASSED', and continue running other tests files. The solution, for me, was to use the return statement.

.
.
.
    if re.match("^[\s\S]*gdm-simple-slave[\s\S]*$", driver.find_element_by_css_selector("BODY").text) == None:
        print "Identifiers object gdm-simple-slave not listed in table"
        return
    else:
        driver.find_element_by_xpath("//input[@value='gdm-simple-slave']").click()
.
.
.

That allowed me to run multiple programs while keeping the debugger running...

test_logsIdentifiersApache2EventWindow.py@16::test_LogsIdentifiersApache2EventWi
ndow **PASSED**
test_logsIdentifiersAudispdEventWindow.py@16::test_LogsIdentifiersAudispdEventWi
ndow **PASSED**
test_logsIdentifiersGdmSimpleSlaveEventWindow.py@16::test_LogsIdentifiersGdmSimp
leSlaveEventWindow Identifiers object gdm-simple-slave not listed in table
**PASSED**
test_logsIdentifiersAuditdEventWindow.py@16::test_LogsIdentifiersAuditdEventWind
ow **PASSED**

Comments

-1

Use try-except statements.

a = [1, 2, 3, 4, 5] 
for x in xrange(0,5):
    try:
        print a[x+1] #this is a faulty statement for test purposes
    except:
        exit()

print "This is the end of the program."

Output:

> python test.py
2
3
4
5

No errors printed, despite the error raised.

6 Comments

exit() still raises SystemError.
I know that, which is why I wrote "despite the error raised."
@EOL You meant SystemExit :)
Despite specificity of the exception handling, an error is raised -- alright, I think we all agree. But he wanted to exit quietly more than anything. By "quiet," I assumed he meant "without showing error. So I agree with you guys, but I wrote the code according to my interpretation of his task.
I see. Yeah, after reading the OP's posts, I realized that. So now, I don't like his question because, to me, it doesn't make much sense. I mean, I get it, but it seems like a shortsighted question. But who's judging...? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.