Module csv_to_graphviz
[hide private]
[frames] | no frames]

Source Code for Module csv_to_graphviz

 1  #! /usr/local/bin/python 
 2  #-*- coding: utf-8 -*- 
 3   
 4  """csv_to_graphviz 
 5   
 6  Charge un fichier CSV et génère un fichier au format DOT pour GraphViz. 
 7  """ 
 8   
 9  __author__ = "Jerome Hussenet, Cedric Bonhomme" 
10  __version__ = "$Revision: 0.1 $" 
11  __date__ = "$Date: 2009/03/06 $" 
12  __copyright__ = "Copyright (c) 2009 Jerome Hussenet, Copyright (c) 2009 Cedric Bonhomme" 
13  __license__ = "Python" 
14   
15  import os 
16  import sys 
17   
18  import csv 
19   
20   
21 -class excel_french(csv.Dialect):
22 delimiter = ';' 23 quotechar = '"' 24 doublequote = True 25 skipinitialspace = False 26 lineterminator = '\n' 27 quoting = csv.QUOTE_MINIMAL
28 csv.register_dialect('excel_french', excel_french) 29 30
31 -def csv_to_graphviz(csv_file, gv_file):
32 """Generate a DOT file for GraphViZ from a CSV file. 33 """ 34 if options.verbose: 35 print "Loading CSV file..." 36 cr = csv.reader(open(csv_file, "rb"), 'excel_french') 37 38 liste_ip, liste = [], [] 39 for ip in cr: 40 liste.append((ip[0], ip[1])) 41 if ip[0] not in liste_ip: 42 liste_ip.append(ip[0]) 43 if ip[1] not in liste_ip: 44 liste_ip.append(ip[1]) 45 46 if options.verbose: 47 print "Creating GraphViz DOT file..." 48 gv_txt = "digraph G {\n" 49 gv_txt += '\tbgcolor=azure;\n' 50 gv_txt += '\tranksep=2;\n' 51 gv_txt += '\tratio=auto;\n' 52 gv_txt += '\tcompound=true;\n' 53 gv_txt += '\tnodesep=5;\n' 54 gv_txt += '\tnode [shape=box, color=lightblue2, style=filled];\n' 55 gv_txt += '\tedge [arrowsize=2, color=gold];\n' 56 for ip in liste_ip: 57 gv_txt += '"' + ip + '"' + ";\n" 58 59 for ip_src, ip_dst in liste: 60 gv_txt += '\t"' + ip_src + '" -> ' + ' "' + ip_dst + '";\n' 61 gv_txt += "}" 62 63 if options.verbose: 64 print "Writting file." 65 gv = open(gv_file, "w") 66 gv.write(gv_txt) 67 gv.close() 68 69 if options.verbose: 70 print "See the result :" 71 print "\tdotty " + gv_file 72 print "\tdot -Tpng -o " + gv_file
73 74 75 if __name__ == "__main__": 76 # Point of entry in execution mode. 77 from optparse import OptionParser 78 parser = OptionParser() 79 parser.add_option("-i", "--input", dest="csv_file", 80 help="CSV file") 81 parser.add_option("-o", "--output", dest="gv_file", 82 help="GraphViz file") 83 parser.add_option("-q", "--quiet", 84 action="store_false", dest="verbose", 85 help="be vewwy quiet (I'm hunting wabbits)") 86 parser.set_defaults(csv_file = './data/ip.csv', 87 gv_file = './data/ip.dot', 88 verbose = True) 89 90 (options, args) = parser.parse_args() 91 92 csv_to_graphviz(options.csv_file, options.gv_file) 93