1 | #!/usr/bin/python2.6 |
---|
2 | |
---|
3 | """ |
---|
4 | Read some whitespace separated data from stdin and pretty print it so that |
---|
5 | the columns line up. |
---|
6 | """ |
---|
7 | |
---|
8 | import sys |
---|
9 | |
---|
10 | def main(): |
---|
11 | pad = "\t" |
---|
12 | align = None |
---|
13 | if len( sys.argv ) > 1: |
---|
14 | pad = " " * int( sys.argv[1] ) |
---|
15 | if len( sys.argv ) > 2: |
---|
16 | align = sys.argv[2] |
---|
17 | rows = [ line.split() for line in sys.stdin ] |
---|
18 | print_tabular( rows, pad, align ) |
---|
19 | |
---|
20 | def print_tabular( rows, pad, align=None ): |
---|
21 | if len( rows ) == 0: return "" |
---|
22 | lengths = [ len( col ) for col in rows[ 0 ] ] |
---|
23 | for row in rows[1:]: |
---|
24 | for i in range( 0, len( row ) ): |
---|
25 | lengths[ i ] = max( lengths[ i ], len( row[ i ] ) ) |
---|
26 | rval = "" |
---|
27 | #for i in range( len( rows[0] ) ): |
---|
28 | # if align and align[ i ] == "l": |
---|
29 | # rval += str( i ).ljust( lengths[ i ] ) |
---|
30 | # else: |
---|
31 | # rval += str( i ).rjust( lengths[ i ] ) |
---|
32 | # rval += pad |
---|
33 | #print rval |
---|
34 | for row in rows: |
---|
35 | rval = "" |
---|
36 | for i in range( 0, len( row ) ): |
---|
37 | if align and align[ i ] == "l": |
---|
38 | rval += row[ i ].ljust( lengths[ i ] ) |
---|
39 | else: |
---|
40 | rval += row[ i ].rjust( lengths[ i ] ) |
---|
41 | rval += pad |
---|
42 | print rval |
---|
43 | |
---|
44 | main() |
---|