Commits

Lars Yencken committed 5950a6d

Uses temporary files instead of dumping files in current dir.

  • Participants
  • Parent commits b444ec3

Comments (0)

Files changed (1)

 import optparse
 import subprocess
 import itertools
+import gzip
+import tempfile
 
 import shell_color
 
 
     n = 0
     for graph, tokens in parses:
-        _dump_dot(graph, filename + '.dot')
-        _render_dot(filename + '.dot', fmt)
-        _display_tokens(tokens)
-        _view_file(filename, fmt)
+        with tempfile.NamedTemporaryFile(suffix='.dot') as dot_file:
+            _dump_dot(graph, dot_file)
+            fmt_file = _render_dot(dot_file.name, fmt)
+            _display_tokens(tokens)
+            _view_file(fmt_file)
+            os.remove(fmt_file)
+
         n += 1
 
     print 'Displayed %d parse graphs' % n
 def _iter_parses(filename):
     "Returns an interator over all valid parses in the file."
     with open(filename) as istream:
+        if filename.endswith('.gz'):
+            istream = gzip.GzipFile(fileobj=istream, mode='r')
         graph, tokens = _find_parse(istream)
         while graph:
             yield graph, tokens
             graph, tokens = _find_parse(istream)
 
-def _view_file(filename, fmt):
+def _view_file(filename):
     "Open the given file in evince, and block until evince closes."
-    retval = os.system('evince %s.%s' % (filename, fmt))
+    retval = os.system('evince %s' % filename)
     if retval != 0:
         sys.exit(1)
 
         print >> sys.stderr, "Dot encountered an error: entering debugger"
         import pdb; pdb.set_trace()
 
-def _dump_dot(graph, filename):
+    return output_name
+
+def _dump_dot(graph, ostream):
     "Dump a graph in dot format."
-    with open(filename, 'w') as ostream:
-        print >> ostream, "digraph G {" 
-        for node, edges in graph.iteritems():
-            # order edges by their order in the sentence
-            edges = edges.items()
-            edges.sort(key=lambda e: int(e[0].split('_')[-1]))
+    print >> ostream, "digraph G {" 
+    for node, edges in graph.iteritems():
+        # order edges by their order in the sentence
+        edges = edges.items()
+        edges.sort(key=lambda e: int(e[0].split('_')[-1]))
 
-            for child, label in edges:
-                print >> ostream, "  %s -> %s [label=\"%s\"]" % (
-                        _normalize_token(node), _normalize_token(child),
-                        label)
-        print >> ostream, "}"
+        for child, label in edges:
+            print >> ostream, "  %s -> %s [label=\"%s\"]" % (
+                    _normalize_token(node), _normalize_token(child),
+                    label)
+    print >> ostream, "}"
+    ostream.flush()
+    assert os.path.exists(ostream.name)
 
 def _normalize_token(name):
     "Rewrites any tokens which would make dot complain."