Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get your hands on exception object caught by default ipython exception handler?

Suppose I'm running some code interactively in IPython and it produces an uncaught exception, like:

In [2]: os.waitpid(1, os.WNOHANG)
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-2-bacc7636b058> in <module>()
----> 1 os.waitpid(1, os.WNOHANG)

OSError: [Errno 10] No child processes

This exception is now intercepted by the default IPython exception handler and produces an error message. Is it possible somehow to extract the exception object that was caught by IPython?

I want to have the same effect as in:

# Typing this into IPython prompt:
try:
    os.waitpid(1, os.WNOHANG)
except Exception, exc:
    pass
# (now I can interact with "exc" variable)

but I want it without this try/except boilerplate.

like image 285
abbot Avatar asked Jul 17 '12 14:07

abbot


People also ask

How do I get exception details in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How does Python handle unknown exception?

When an exception occurs, the Python interpreter stops the current process. It is handled by passing through the calling process. If not, the program will crash. For instance, a Python program has a function X that calls function Y, which in turn calls function Z.

What is exception how it is handled in Python?

An Exception is an error that happens during the execution of a program. Whenever there is an error, Python generates an exception that could be handled. It basically prevents the program from getting crashed.


1 Answers

I think sys.last_value should do the trick:

In [8]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)

/home/ubuntu/<ipython console> in <module>()

ZeroDivisionError: integer division or modulo by zero

In [11]: sys.last_value
Out[11]: ZeroDivisionError('integer division or modulo by zero',)

If you want even more fun with such things, checkout the traceback module, but that probably won't be of much use within ipython.

like image 171
Will Avatar answered Sep 21 '22 15:09

Will