Tag Archives: python

create graphviz image from textfile

inspired by text2mindmap.com i decided to create something similar in python.

Here’s the result:

Code text2mindmap.py

#!/usr/bin/python
 
import pydot
import sys
 
 
def ReadFile(filename):
  fh = open(filename)
  return [x.rstrip() for x in fh.readlines()]
 
 
def CreateEdges(lines):
  edge_list= ['' for x in range(100)]
 
  edges = []
  for line in lines:
    pos = line.count('\t');
    edge_list[pos] = line.replace('\t', '')
    if pos:
      edges.append((edge_list[pos -1], edge_list[pos]))
  return edges
 
 
def CreateGraphFromEdges(edges, output):
  g=pydot.graph_from_edges(edges, directed=True)
  return g.write_png('%s.png' % output, prog='dot')    
 
 
def main(argv):
  CreateGraphFromEdges(CreateEdges(ReadFile(argv[1])), argv[2])
 
 
if __name__ == "__main__":
   main(sys.argv)

Source file months.txt

Months of the year
	Spring
		March
		April
		May
	Summer
		June
		July
		August
	Autumn
		September
		October
		November
	Winter
		December
		January
		February

How to generate the image:

$ ./text2mindmap.py months.txt months

pydot + graphviz

Install pydot
Install graphviz

$ python
Python 2.5.1 (r251:54863, Feb  9 2009, 18:49:36) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pydot
>>> edges=[('1','2'), ('1','3'), ('1','4'), ('3','4')]
>>> g=pydot.graph_from_edges(edges)
>>> g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')
True
>>>

result:
example

Python debugging with pdb

The typical usage to break into the debugger from a running program is to insert

import pdb; pdb.set_trace()

at the location you want to break into the debugger. You can then step through the code following this statement, and continue running without the debugger using the c command.

The typical usage to inspect a crashed program is:

>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "./mymodule.py", line 4, in test
    test2()
  File "./mymodule.py", line 3, in test2
    print spam
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
</stdin>