在IPython中隐藏所有警告
我想录制一个IPython会话的视频,但为了不让观众感到困惑,我想关闭所有来自不同软件包的警告信息。这些警告是通过warnings.warn
这个函数发出的。请问有没有办法在ipythonrc文件中设置,让这些警告自动关闭呢?
5 个回答
14
这个被接受的答案在Jupyter中不管用(至少在使用某些库的时候)。
这里的JavaScript解决方案只是隐藏了已经显示的警告,而不是将来可能会显示的警告。
为了在Jupyter和JupyterLab中隐藏或显示警告,我写了下面这个脚本,基本上是通过切换CSS来隐藏或显示警告。
%%javascript
(function(on) {
const e = $("<a>Setup failed</a>");
const ns = "js_jupyter_suppress_warnings";
var cssrules = $("#" + ns);
if(!cssrules.length)
cssrules = $("<style id='" + ns + "' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s = 'Showing';
cssrules.empty()
if(on) {
s = 'Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s + ' warnings (click to toggle)');
on = !on;
}).click();
$(element).append(e);
})(true);
65
我通过在一个单元格里运行以下代码来隐藏粉色框里的警告:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
1236
位置:
import warnings
warnings.filterwarnings('ignore')
在 ~/.ipython/profile_default/startup/disable-warnings.py
里面。
有时候,看到一个警告信息是很有用的,尤其是只想看一次的时候。你可以通过以下方式来设置:
warnings.filterwarnings(action='once')