Nick Taber
Nick Taber

Reputation: 187

Stop Python code without an error

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.

Upvotes: 3

Views: 14990

Answers (5)

rwbyrd
rwbyrd

Reputation: 416

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**

Upvotes: 0

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94485

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

Upvotes: 12

jurgenreza
jurgenreza

Reputation: 6086

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.

Upvotes: 2

Mr_Spock
Mr_Spock

Reputation: 3835

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.

Upvotes: -1

Captain Skyhawk
Captain Skyhawk

Reputation: 3500

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

import os
os._exit(1)

Upvotes: 6

Related Questions