Exit failed script run (python)

I saw several questions about exiting the script after the task completed successfully, but is there a way to do the same for the script that failed? I am writing a testing script that just checks the camera is working properly. If the first test fails, it is more than likely that the following tests will also fail; therefore, I want the first failure to cause an output and display output, letting me know that an error has occurred.

Hope this is enough information; let me know if you need more information.

+6
python exception exit
source share
4 answers

Are you just looking for exit() function?

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

The exit() parameter is the return code that the script will return to the shell. Typically, values โ€‹โ€‹other than 0 indicate an error.

+19
source share

You can use sys.exit() to exit. However, if any of the code above catches a SystemExit exception, it will not fail.

+3
source share

You can create exceptions to determine error conditions. Your top-level code can catch these exceptions and handle them accordingly. You can use sys.exit to exit. For example, 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) 
+1
source share

You want to check the return code from the C ++ program that you are using and exit if it indicates a failure. In the code below, / bin / false and / bin / true are programs that exit with errors 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 are running ends with zero success, other than zero on failure.

0
source share

All Articles