Source

grrdrr / src / grrdrr / graphviz.py

Full commit

from model import ensure, WithNodeLabel
import StringIO
import subprocess


def draw_graphviz(graph, stream):
    ensure(graph.readonly(WithNodeLabel), "without node labels", graph)
    io = StringIO.StringIO()
    print >>io, 'digraph "_" {'
    print >>io, '  node [shape=box];'
    for node in graph.nodes:
        print >>io, '  "%s";' % node.label.text
    for arc in graph.arcs:
        print >>io, '  "%s" -> "%s";' % (arc.target.label.text, arc.origin.label.text)
    print >>io, "}"
    cmd = ["dot", "-Tpng"]
    process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate(io.getvalue())
    if process.returncode != 0:
        raise RuntimeError("graphviz returned non-zero error code: %s (%r)" % (process.returncode, err))
    stream.write(out)