如何在 Python 3 中抑制 graphviz 警告?

How to suppress graphviz warnings in Python 3?

我正在使用 graphviz 模块来呈现节点和链接网络。

我使用小圆圈作为节点的形状,所以标签故意比节点大。

因此,我收到以下警告:

"Warning: node 'wave', graph 'N' size too small for label"

'Wave'只是一个节点标签的例子。

我得到了很多这个warnings because of the high quantity of nodes (screencapture).

所以,我的问题是:我怎样才能抑制这样的警告?

我使用的 graphviz 命令是:

n.view()  # n is my digraph

我已经尝试过以下建议:

How to suppress a third-party warning using warnings.filterwarnings

How to redirect python warnings to a custom stream?

但目前还没有。 提前致谢。

试试 Eli Bendersky 的优秀页面:Redirecting all kinds of stdout in Python

stdout 替换为 stderr 后,Eli 的解决方案对我适用于 graphviz。

如果您恰好在使用 Evince、Ubuntu 的内置 PDF 查看器,请参阅:

https://superuser.com/questions/980237/silence-evinces-warnings-in-ubuntu

对于 graphviz,从 v0.11 开始,.draw() 方法有一个 silent 选项(参见 graphviz docs:graphviz.view)。

显然不在 windows。


这适用于那些使用 networkx(使用 pygraphviz)或 pygraphviz 的人。

在 pygraphviz 中,收集警告然后使用 warnings module (see pygraphviz/agraph.py:1390).

推送

因此,您可以在绘图时专门关闭警告: warnings docs:Temporarily Suppressing Warnings

import warnings

<create graph etc>

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    g.draw()