turn warning off in a cell jupyter notebook turn warning off in a cell jupyter notebook python-3.x python-3.x

turn warning off in a cell jupyter notebook


Write %%capture as the first line of the cell to catch cell output. You can use the options --no-stderr, --no-stdout, --no-display, and --output to control which cell outputs will be caught. See more details here.


Normally I want to keep stdout open for printing so I find using catch_warnings like this better:

import warningsdef action_with_warnings():    warnings.warn("should not appear")with warnings.catch_warnings(record=True):    action_with_warnings()

It has the disadvantage of storing the warnings in memory, but it is normally not a significant overhead and worth the simplicity. Even within a single cell I find having fine grained control means warnings I do care about are not accidentlly missed.


Solutions:

Usually there is no need to extend the effect to the whole cell, as this may hide some other useful message, so use a context manager to ignore the warnings:

with warnings.catch_warnings():    warnings.simplefilter('ignore')    # Your problematic instruction(s) here

If there are good reasons to protect the whole cell then simply prevent the stderr stream to be displayed in the cell output area by inserting the capture "magic":

`%%capture --no-stderr`

at the top of the cell (rather than indenting all lines).


Explanations:

The most logical way is to insert the code triggering a warning within a context manager introduced by keyword with. It switches off and restore the warning system prior and after the problematic code

Python provides such context manager as warnings.catch_warnings:

A context manager that copies and, upon exit, restores thewarnings filter and the showwarning() function. If therecord argument is False (the default) the context managerreturns None on entry. If record is True, a list isreturned that is progressively populated with objects as seen bya custom showwarning() function (which also suppresses outputto sys.stdout).

You also need to register a filter to react to each warning captured by the context manager, else the default filter remains active.

Python provides the warnings.simplefilter which:

Insert a simple entry into the list of warnings filterspecifications

It registers some action (ignore for no action, always to print the warning message, etc, see full description).

Example:

import warnings, mathimport numpy as np# We want to compute the logs of this sequence.# But log isn't defined for values <= 0s = [-1, 5, 2, 0]with warnings.catch_warnings():    warnings.simplefilter('ignore')    r = np.log(s)print(r)