Take the 2-minute tour ×

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!

share|improve this question
Are you talking about tests using the unittest module? –  bstpierre Jul 24 '09 at 17:38
No, my python script is actually calling a C++ program, which runs the tests. In the event the camera is not on or the lens is on, the script doesn't respond very well. I want my script to quit trying if either is the case. There could be other obstacles hindering the tests, so I would like to design my script such that any error would cause the script to quit. –  Ariel Stark Jul 24 '09 at 17:45

4 Answers 4

Are you just looking for the exit() function?

import sys

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

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

share|improve this answer
my script looks like this: import sys try: # loop function... raise SystemExit except: print 'error' sys.exit() #fairly redundant due to the previous raise statement The 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 –  Ariel Stark Jul 24 '09 at 17:39
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 Jul 24 '09 at 17:50
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) –  Ariel Stark Jul 24 '09 at 21:35
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... –  Ariel Stark Jul 24 '09 at 22:13
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 Jul 24 '09 at 22:32

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

share|improve this answer

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

def camera_test_1():

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

if __name__ == '__main__':
        print 'Camera successfully initialized'
    except CameraInitializationError, e:
        print >>sys.stderr, 'ERROR: %s' % e
share|improve this answer
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? –  Ariel Stark Jul 24 '09 at 17:42
Sure. You can catch a higher level exception like StandardError or Exception or you can catch everything with `except:'. –  Ryan Bright Jul 25 '09 at 22:50

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'

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

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

share|improve this answer

Your Answer

