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.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Nick Taber
  • 177
  • 1
  • 2
  • 10

5 Answers5

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

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • I don't know! seriously! maybe the same person that down voted my answer. – jurgenreza Apr 28 '13 at 04:04
  • 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. – Nick Taber Apr 28 '13 at 04:05
  • Is `exit()` same as `os._exit()`? – jurgenreza Apr 28 '13 at 05:01
  • @jurgenreza, if you are referring to `sys.exit()`, then, no, they are different, as explained in the answer. – Eric O. Lebigot Apr 28 '13 at 09:52
  • @EOL No i am referring to `exit()`. – jurgenreza Apr 28 '13 at 15:22
  • If you are referring to the built-in `exit()` which is added when the interpreter is run without the -S option, then `exit()` is *different* from `os._exit()`. `exit()` is similar to `sys.exit()`: [it raises SystemExit](http://docs.python.org/3/library/constants.html#constants-added-by-the-site-module). Note that it is [not recommended](http://docs.python.org/3/library/constants.html#constants-added-by-the-site-module) to use it in programs. – Eric O. Lebigot Apr 29 '13 at 03:36
6

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

import os
os._exit(1)
Captain Skyhawk
  • 3,499
  • 2
  • 25
  • 39
  • This function is bad and you shouldn't be using it – JBernardo Apr 28 '13 at 02:41
  • why did you suggest os._exit and not sys.exit? http://stackoverflow.com/questions/9591350/what-is-difference-between-sys-exit0-and-os-exit0 – Paul Apr 28 '13 at 02:49
  • 2
    @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. – Captain Skyhawk Apr 28 '13 at 02:55
  • 1
    @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. – Eric O. Lebigot Apr 28 '13 at 03:12
  • You can loose data on open files and other crazy stuff may happen – JBernardo Apr 28 '13 at 03:30
  • 1
    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. – Dannie Dec 13 '18 at 12:59
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.

jurgenreza
  • 5,856
  • 2
  • 25
  • 37
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**
Mörre
  • 5,699
  • 6
  • 38
  • 63
rwbyrd
  • 416
  • 5
  • 24
-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.

Mr_Spock
  • 3,815
  • 6
  • 25
  • 33
  • `exit()` still raises `SystemError`. – Eric O. Lebigot Apr 28 '13 at 03:15
  • I know that, which is why I wrote "despite the error raised." – Mr_Spock Apr 28 '13 at 03:17
  • @EOL You meant `SystemExit` :) – JBernardo Apr 28 '13 at 03:38
  • 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. – Mr_Spock Apr 28 '13 at 03:47
  • @Mr_Spock: the code in the question does not show an error per se either (it only prints a string): I understand that the problem is not to write code that does not raise an (non-SystemExit) exception, but to either exit unconditionally or to handle SystemExit silently. – Eric O. Lebigot Apr 28 '13 at 03:54
  • 1
    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...? :) – Mr_Spock Apr 28 '13 at 04:28