I have a script containing a section similar to this, on Python 2.6:
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except:
print 'exception occurred, exiting with error'
sys.exit(1)
I noticed that though it was printing the 'is the same' line, it also logs the exception!
If you remove the try/except block, the interpreter shows no error. If you catch a specific error like ValueError, the except block is not executed.
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except Exception as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
The except block is not executed, and the process finishes with return code 0. So, the exception is above Exception in the hierarchy?
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except BaseException as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
produces
cow is the same as cow exception occurred, exiting with error.
Exception is: (0,)
And the process finishes with exit code 1.
Why is this Except block being executed at all?
sys.exit() raises SystemExit, which is what you're seeing.
As to why it doesn't inherit from Exception:
The exception inherits from BaseException instead of StandardError or
Exception so that it is not accidentally caught by code that catches
Exception. This allows the exception to properly propagate up and cause the interpreter to exit.
sys.exit() simply raises SystemExit. That's how it exits the program. When you catch all exceptions, you also catch SystemExit.
In addition to other answers: SystemExit does not inherit from Exception, python exception hierarchy: http://docs.python.org/library/exceptions.html
Related
I managed to catch the termination with:
atexit.register(exitHandler)
But how to print out what happened on that point? I want to see if the program aborts due to an error, due to Crtl-C or normal stopping...
It's not the complete solution - but you could wrap code in try except
try:
YOUR CODE HERE
except Exception as e:
print(e)
You should catch KeyboardInterrupt for Ctrl-C. E.g.:
import sys
try:
# your code
except KeyboardInterrupt:
sys.exit('Abort by user interrupt')
except Exception as exc:
sys.exit(f'Abort on error: {exc}')
I have a simple script:
i=1
while True:
try:
print i
except KeyboardInterrupt:
raise Exception("Ended by user.")
i = i+1
and when I interrupt it, it prints out:
How can I have it just print out the last line "Exception: Ended by user.", and not the "Traceback..." statement.
to emulate the exception but without the traceback, you could just print a message and exit with a non-zero code:
except KeyboardInterrupt:
print("Ended by user.")
sys.exit(1)
In the code below, Whenever exception is caught, I would like to exit from the program & print the exception on shell
#stream.py
import hashlib
import sys
import os
import importlib
for line in sys.stdin.readlines():
try:
inpFile = "temp.py"
execfile(inpFile)
line1 = line.strip('\n').split('\t')
print "\t".join(line1)
except:
#exception expected "temp.py:File Not Found", how do I exit the code & print the exception on console ?
sys.exit(1)
Here is the Transform query to call the UDF:
Create table newtable as Select TRANSFORM(id,name) USING
'python stream.py' as (id,name) from mytable;
ideas appreciated.
if you want to catch a specific type of exception (for examle an IOError) you can use
except IOError as e:
and access the error string with e.strerror
if you want to catch all exception you can use sys.exc_info()[0] to access the last error message
for example
try:
1/0
except:
print sys.exc_info()[0]
would print
<type 'exceptions.ZeroDivisionError'>
If you are expecting a specific exception then you should trap that, not everything, which is what you are doing. But there is nothing in your code to generate a "File Not Found" anyway!
EDIT: question code changed! We really do wish to trap "everything". I am using Exception, which traps "almost" everything, see https://docs.python.org/2/library/exceptions.html
This uses Python 2 syntax:
import sys
for line in sys.stdin.readlines():
try:
inpFile = "temp.py"
execfile(inpFile)
line1 = line.strip('\n').split('\t')
print "\t".join(line1)
except Exception as err:
print >> sys.stderr, err # print to stderr (python 2 syntax)
sys.exit(1)
I want to exit Python if I encounter an exception in my function if that function is being executed from the command line, but want to raise an exception and print a stack trace if the my function is not run from the command line.
Right now I have
try:
#...
except Exception as e:
print('ERROR: Some useful message')
if __name__ == '__main__':
raise SystemExit
else:
raise e
but I feel like I'm either doing too much here, or too little.
Is there an idiomatic way to get a stack trace with the original exception when my function is run from the command line; but simply exit if it is being run from the command line?
The better way would be to do this:
import sys
def func():
do_actual_processing()
if not successful:
raise Exception("Yadayada")
if __name__ == '__main__'
try:
func()
except Exception as e:
sys.exit(1)
That is, the function itself does not need to be concerned with whether or not it is run from command line.
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.
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.
You can use sys.exit() to exit. However, if any code higher up catches the SystemExit exception, it won't exit.
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)
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.