Skip to content

Commit

Permalink
Pretty print (#26)
Browse files Browse the repository at this point in the history
* add support for pretty-printing

* bump release number
  • Loading branch information
jamesscottbrown authored Jan 18, 2020
1 parent b878ced commit 30931bf
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,18 @@ g.add_node('foobar', label="""Multi
g.add_edge('foo', 'foo1', label="EDGE!", width="3.0", color="#0000FF",
arrowhead="white_diamond", arrowfoot="standard", line_type="dotted")

print g.get_graph()
print(g.get_graph())

# To write to file:
with open('test_graph.graphml', 'w') as fp:
fp.write(g.get_graph())

# Or:
g.write_graph('example.graphml')

# Or, to pretty-print with whitespace:
g.write_graph('pretty_example.graphml', pretty_print=True)

```

Saving this to a file with a ``.graphml`` extension, opening in yEd, applying ``Tools -> Fit Node to Label`` and ``Layout -> One-click layout`` produces something like the following:
Expand Down
14 changes: 11 additions & 3 deletions pyyed/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys
import xml.etree.ElementTree as ET
from xml.dom import minidom

node_shapes = ["rectangle", "rectangle3d", "roundrectangle", "diamond", "ellipse",
"fatarrow", "fatarrow2", "hexagon", "octagon", "parallelogram",
Expand Down Expand Up @@ -333,10 +334,17 @@ def construct_graphml(self):

self.graphml = graphml

def write_graph(self, filename):
def write_graph(self, filename, pretty_print=False):
self.construct_graphml()
tree = ET.ElementTree(self.graphml)
tree.write(filename)

if pretty_print:
raw_str = ET.tostring(self.graphml)
pretty_str = minidom.parseString(raw_str).toprettyxml()
with open(filename, 'w') as f:
f.write(pretty_str)
else:
tree = ET.ElementTree(self.graphml)
tree.write(filename)

def get_graph(self):
self.construct_graphml()
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


setup(name='pyyed',
version='1.2',
version='1.3',
description='A simple Python library to export graphs to the yEd graph editor',

author='James Scott-Brown',
Expand Down

0 comments on commit 30931bf

Please sign in to comment.