pythonpython-3.xgraphvizimage-graphviz

Convert Digraph to StringIO with graphviz


Does anyone know a trick how to convert a Digraph into a io.StringIO png? The only code I could find is to save it to disk, but I would like to leave out any disk usage and to process it in memory instead:

from graphviz import Digraph
import io

dot = Digraph(comment='The Round Table')
dot.node('A', 'King Arthur')

# instead of this...
dot.render('test-output/round-table.gv', view=True)

# ... I need something like this:
data = io.StringIO()
dot.export_to_png(dot)

Solution

  • Something like this?

    from graphviz import Digraph
    import io
    
    dot = Digraph(comment='The Round Table', format='gv')
    dot.node('A', 'King Arthur')
    
    data = io.StringIO()
    
    print("writing")
    data.write( dot.pipe().decode('utf-8') )
    
    print("reading")
    data.seek(0)
    print(data.read())
    
    # print(data.getvalue())
    
    
    data.close()