Refactor table printing into a function.
David Blume

David Blume commited on 2016-09-11 14:15:17
Showing 1 changed files, with 29 additions and 19 deletions.

... ...
@@ -71,6 +71,33 @@ def map_key_to_prefix(k):
71 71
         pass
72 72
     return ""
73 73
 
74
+
75
+def print_as_table(rows, underline_header = True):
76
+    """ Prints rows with consistent column widths. """
77
+    cols = zip(*rows)
78
+
79
+    # Compute column widths by taking maximum length of values per column
80
+    col_widths = [max(len(value) for value in col) for col in cols]
81
+
82
+    # Create a suitable format string for nice table output
83
+    fmt = "\t".join(["{:<%d}" % i for i in col_widths])
84
+
85
+    # Print each row using the computed format
86
+    if underline_header:
87
+        print fmt.format(*rows.pop(0))
88
+        print "\t".join([('-' * i) for i in col_widths])  # column header separator
89
+    for row in rows:
90
+        print fmt.format(*row)
91
+
92
+
93
+def print_footer():
94
+    print
95
+    print 'Tip:'
96
+    print 'sync_ip () { export ENV_VAR=$(curl -s "%s?k=YP008G581095,2N00FG504225"); }' % os.environ['SCRIPT_URI']
97
+    print 'curl --data "`hostname -s`=`hostname -i`&auth=$AUTH" "%s"' % os.environ['SCRIPT_URI']
98
+    print 'Source code at http://git.dlma.com/kvs.git/'
99
+
100
+
74 101
 if __name__ == '__main__':
75 102
     localdir = os.path.abspath(os.path.dirname(sys.argv[0]))
76 103
     args = cgi.FieldStorage()
... ...
@@ -145,25 +172,8 @@ if __name__ == '__main__':
145 172
                 rows.append((key, d['value'], created, str(d['time']), origin,
146 173
                             "%supdated %s ago" % (map_key_to_prefix(key), td)))
147 174
 
148
-            cols = zip(*rows)
149
-
150
-            # Compute column widths by taking maximum length of values per column
151
-            col_widths = [max(len(value) for value in col) for col in cols]
152
-
153
-            # Create a suitable format string for nice table output
154
-            fmt = "\t".join(["{:<%d}" % i for i in col_widths])
155
-
156
-            # Print each row using the computed format
157
-            print fmt.format(*rows.pop(0))
158
-            print "\t".join([('-' * i) for i in col_widths])  # column header separator
159
-            for row in rows:
160
-                print fmt.format(*row)
161
-
162
-            print
163
-            print 'Tip:'
164
-            print 'sync_ip () { export ENV_VAR=$(curl -s "%s?k=YP008G581095,2N00FG504225"); }' % os.environ['SCRIPT_URI']
165
-            print 'curl --data "`hostname -s`=`hostname -i`&auth=$AUTH" "%s"' % os.environ['SCRIPT_URI']
166
-            print 'Source code at http://git.dlma.com/kvs.git/'
175
+            print_as_table(rows)
176
+            print_footer()
167 177
 
168 178
         if not wrote_response:
169 179
             print 'Status: 400 Bad Request\n'
170 180