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)
Related
I am trying to custimize my error codes in a script that I am writing and I was wondering if I can adjust the output. Here is the scenario. Running this script:
while True:
try:
x = "Hello World"
int(x)
except (ValueError, RuntimeError, TypeError, NameError, SystemExit):
sys.exit("Error: Check Section 1.0")
Creates an output of:
An exception has occurred, use %tb to see the full traceback.
SystemExit: Error: Check Section 1.0
Is there an easy way, when an error occurs, the script stops and only says:
Error: Check Section 1.0
Just do print and do break since you keep it inside a loop
while True:
try:
x = "Hello World"
int(x)
except:
print("Error: Check Section 1.0")
break
Try this instead, this method direct shows you "Error: Check Section 1.0" only.
while True:
try:
x = "Hello World"
int(x)
except:
sys.exit("Error: Check Section 1.0")
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}')
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'am writing console program. I want that save flow may break with Cntr-c only after answer on question: Do you really want break it?
def sigint_handler(signal, frame):
try:
Exit = (str(raw_input("Break ? Y/N")))
if Exit == "Y" or Exit=="y":
raise KeyboardInterrupt()
except KeyboardInterrupt:
raise KeyboardInterrupt()
except Exception as e:
pass
signal.signal(signal.SIGINT,sigint_handler)
i=0
while i<1000:
i=i+1
print "%d\n"%i
sleep(0.5)
It's fail if I try cntl+c instead of Y:
71
72
73
74
75
^CBreak ? Y/Ny
File "/home.local/valerys/rde_1_3/rdepyui/bin/../api/cli.py", line
48, in sigint_handler
Exit = (str(raw_input("Break ? Y/N"))) RuntimeError: can't re-enter readline
Why do you make a re-raise of KeyboardInterrupt in the except block? In this way you catch the first KeyboardInterrupt but you don't have another try/except block for catching the second. Maybe a better solution is to call
try:
Exit = (str(raw_input("Break ? Y/N")))
if Exit == "Y" or Exit=="y":
raise KeyboardInterrupt()
except KeyboardInterrupt:
sys.exit()
for a clean exit strategy.
I hope this can help you.
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