Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPython notebook avoid printing within a function

I want to prevent a function to print in iPython notebook.

In standard python one can prevent printing some lines of code as answered in the question: To prevent a function from printing in the batch console in Python However this method do not work in iPython notebook, losing the output until a restart of the Kernel.

The most similar feature I found is to avoid a full cell to display using the magic function:

%%capture capt

However this magic function blocks the whole cell, is there any way in iPython notebook to avoid printing just some of the lines within the code?

like image 718
David Mabodo Avatar asked May 12 '14 13:05

David Mabodo


People also ask

How do I suppress output in a python notebook?

Put a ; at the end of a line to suppress the printing of output [Reference].

How do you not output in a Jupyter Notebook?

Suppress functions print output If you want to stop the messages from print function with Jupyter Notebook you can use: %%capture.

What does %% capture do python?

IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.

What does %% do in Jupyter Notebook?

IPython Magic – Timing These are especially handy when you have some slow code and you're trying to indentify where the issue is. %%time will give you information about a single run of the code in your cell.


1 Answers

You could use io.capture_output:

from IPython.utils import io

with io.capture_output() as captured:
    foo()

to capture stdout and stderr for only those lines within the with-statement.

like image 135
unutbu Avatar answered Nov 01 '22 19:11

unutbu