views:

532

answers:

4

I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.

I hope this is enough information; let me know if more details are required to help me.

Thank you!

+3  A: 

Are you just looking for the exit() function?

import sys

if 1 < 0:
  print >> sys.stderr, "Something is seriously wrong."
  sys.exit(1)

The (optional) parameter of exit() is the return code the script will return to the shell. Usually values different than 0 signal an error.

sth
my script looks like this:import systry: # loop function... raise SystemExitexcept: print 'error' sys.exit() #fairly redundant due to the previous raise statementThe raise system forces the script to stop running with or without an error. Then when I take it out and leave the sys.exit(), it allows the entire script to run and then reports there was an error. How could I use your answer to help?I am a new python user. What do you mean by if 1<0? Is it supposed to represent a condition, and I am just reading too far into it?Thanks Again
`if 1<0` was just an example for an error condition in which case you would want to abort the further execution. I'm not really sure what exactly you need help with: `print` prints an error message and `sys.exit()` exits the script, isn't that all it needs to do? What would you want to work differently? Why search for a more complicated solution if a simple one does all that's needed?
sth
I think my problem is that I do not know how to define the errors that could occur. The except portion of the try statement is not operating the way I expected it to... (recognize any error and respond accordingly)
For example, I tested this method on a short script that merely divided 4 by a series of numbers starting with 0. The execution was disturbed because of division by 0. In this instance the except worked because of an already defined condition, whereas the camera test continues running. I can verbalize what the error is (in English), but I do not know what the computer needs to hear if that makes any sense...
So the main problem is to detect in the script that the error happened? Where does the error happen and what effects does it have (in English)? Does the error happen in the C++ program you mentioned?
sth
The error was the camera was not on. When it is not on, neither program can read what mode it is in. And if I run the script and the camera is not on, the camera will not be on for the subsequent tests; that's why I want the script to just quit.At any rate, I stumbled upon a solution from looking at it over and over again and reading all the answers here.Thank you!
A: 

You can use sys.exit() to exit. However, if any code higher up catches the SystemExit exception, it won't exit.

Adam Rosenfield
A: 

You can raise exceptions to identify error conditions. Your top-level code can catch those exceptions and handle them appropriately. You can use sys.exit to exit. E.g., in Python 2.x:

import sys

class CameraInitializationError(StandardError):
    pass

def camera_test_1():
    pass

def camera_test_2():
    raise CameraInitializationError('Failed to initialize camera')

if __name__ == '__main__':
    try:
        camera_test_1()
        camera_test_2()
        print 'Camera successfully initialized'
    except CameraInitializationError, e:
        print >>sys.stderr, 'ERROR: %s' % e
        sys.exit(1)
Ryan Bright
Thank you for your response.Could I do something similar which would stop the script regardless of what the error is? If so, how do I set that up?
Sure. You can catch a higher level exception like StandardError or Exception or you can catch everything with `except:'.
Ryan Bright
A: 

You want to check the return code from the c++ program you are running, and exit if it indicates failure. In the code below, /bin/false and /bin/true are programs that exit with error and success codes, respectively. Replace them with your own program.

import os
import sys

status = os.system('/bin/true')
if status != 0:
    # Failure occurred, exit.
    print 'true returned error'
    sys.exit(1)

status = os.system('/bin/false')
if status != 0:
    # Failure occurred, exit.
    print 'false returned error'
    sys.exit(1)

This assumes that the program you're running exits with zero on success, nonzero on failure.

bstpierre