Search code examples
pythongraphvizpydotanytree

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


This question is based on Tarun's Answer for rendering a tree in python using anytree and graphviz: https://stackoverflow.com/a/49442969/2139007

After installing graphviz and adding it to my PATH variables i'am trying to run the following python code:

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

The above code generates the following error:

  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.

The problem does not occure if I run the dot command 'dot tree.dot -T png -o tree.png' manually from the console after generating a .dot file

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

Is there a way to solve this?


Solution

  • I just ran into this problem. After 2 hours of debugging, I found out for Windows, you have to set the delete flag to False in dotexporter.py. Go to line 224 in "dotexporter.py" and make the following change. It seems like a bug in the source file. This worked for me:

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