Programmatically get current IPython notebook cell output?

Question:

I have an imported function that runs in an IPython notebook (input cell X) which produces an output (in output cell X). After the function runs, I have some more code (also in input cell X); is there any way for that code to retrieve the current output (in output cell X)?

There may be other ways to do what I am trying to achieve; but I am curious if the above is possible.

Asked By: killajoule

||

Answers:

IPython’s output caching system defines several global variables:

  • [_] (a single underscore): stores previous output, like Python’s default interpreter.
  • [__] (two underscores): next previous.
  • [___] (three underscores): next-next previous.

Additionally, after each output x is created, there is a variable _<x> created with the output as its value. For example:

In [12]: lst = [i for i in range(11)]

In [13]: lst
Out[13]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [14]: _13
Out[14]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Also, if you’re interested, _i<x> contains the contents of the input cell x:

In [15]: _i12
Out[15]: 'lst = [i for i in range(11)]'
Answered By: MattDMo

You can get the output of the cell X by using _ or Out[X]. Such as:

In [1]: 2 + 35
Out[1]: 37
In [2]: _ + 3
Out[2]: 40 
In [3]: lst = [i for i in range(5)]
        lst
Out[3]: [0, 1, 2, 3, 4]
In [4]: Out[1] #Using the output of Cell 1
Out[4]: 37
In [5]: Out[3][1] #Using the output of Cell 3
Out[5]: 1

Here, If you want to get the output of the previous cell, then you can use _. You can use two (__) or three underscores(___) as well to refer to output of the next previous and next-next previous cells respectively.

However, if you have many cells in the notebook and you want to refer some particular cell, then Out[X] will be helpful.

Answered By: Jay Patel

The existing answers don’t work for when a cell calls a function that generates its own stdout.

I found a different solution that catches all of the output of the previous cell, no matter how it was produced.

# cell 1:
%%capture output
print("blah")
func_that_prints("Bha")
# -----------------
# cell 2:
prev_cell_output = str(output)
# do something with prev_cell_output

Note that %%capture line must the very first line of a cell for it to work. output can be renamed to any other variable name. There will be no output for the first cell displayed (as it’ll be captured).

output becomes available only in the following cell. It is a utils.io.CapturedIO object, so you can stringify it, or even call .show() on it, which will display its contents.

For more information, e.g. capturing just stdout, or just stderr use the reference.

Answered By: stason
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.