使用 Anytree 和 graphviz 在 python 中渲染一棵树。无法打开文件

Rendering a tree in python with Anytree and graphviz. Can't open file

此问题基于 Ta运行 在 python 中使用 anytree 和 graphviz 渲染树的答案:

安装 graphviz 并将其添加到我的 PATH 变量后,我正在尝试 运行 以下 python 代码:

DotExporter(nodes[0]["a"],
        nodeattrfunc=lambda node: 'label="{}"'.format(node.display_name)).to_picture("tree.png")

以上代码产生以下错误:

  Error: dot: can't open C:\Users\username\AppData\Local\Temp\tmpa7t554le
Traceback (most recent call last):
  File "D:\mypath\tree.py", line 34, in <module>
    dot.to_picture('tree.png')
  File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\site-packages\anytree\exporter\dotexporter.py", line 229, in to_picture
    check_call(cmd)
  File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 291, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['dot', 'C:\Users\username\AppData\Local\Temp\tmpa7t554le', '-T', 'png', '-o', 'tree.png']' returned non-zero exit status 2.

如果我 运行 点命令 'dot tree.dot -T png -o tree.png' 手动从生成 .dot 文件后的控制台

DotExporter(nodes[0]["a"],
        nodeattrfunc=lambda node: 'label="{}"'.format(node.display_name)).to_dotfile('tree.dot')

有办法解决吗?

我刚刚 运行 遇到了这个问题。经过2个小时的调试,我发现Windows,你必须在dotexporter.py中将删除标志设置为False。转到 "dotexporter.py" 中的第 224 行并进行以下更改。这似乎是源文件中的错误。这对我有用:

 with NamedTemporaryFile("wb", delete=False) as dotfile:

这在某种程度上是 windows 和 python 临时文件句柄的意外行为。请只使用最新的 anytree 版本 (https://anytree.readthedocs.io/en/latest/)。它包含一个修复程序。