Python print last traceback only?
Asked Answered
L

1

15

Consider the following code and traceback:

>>> try:
...  raise KeyboardInterrupt
... except KeyboardInterrupt:
...  raise Exception
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Exception
>>> 

I'd like to print only the most recent traceback (the one in which Exception was raised).
How can this be achieved?


From the above example, I'd like to print the following, as if raise Exception had been called outside the except clause.

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
Exception
Lyle answered 19/12, 2013 at 9:34 Comment(2)
By "get", do you mean get the exception object, or do you mean not printing the context information? If you mean the second, do you want some sort of global interpreter setting, or something that applies to specific exceptions?Balsamiferous
Raising exceptions when an exception is already present in Python 3Chen
M
34

The perfect question for me.

You can suppress the exception context, that is the first part of the traceback, by explicitly raising the exception from None:

>>> try:
        raise KeyboardInterrupt
    except:
        raise Exception from None

Traceback (most recent call last):
  File "<pyshell#4>", line 4, in <module>
    raise Exception from None
Exception

This was formalized in PEP 409 and further improved in PEP 415. The original bug request for this was filed by myself btw.


Note that suppressing the context will not actually remove the context from the new exception. So you can still access the original exception:

try:
    try:
        raise Exception('inner')
    except:
        raise Exception('outer') from None
except Exception as e:
    print(e.__context__) # inner
Mccloud answered 19/12, 2013 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.