| 1 | #!/usr/bin/python2.6 | 
|---|
| 2 |  | 
|---|
| 3 | """ | 
|---|
| 4 | Tool for adding a column to a table. Expressions for the column are similar | 
|---|
| 5 | to those supported by table_filter.py | 
|---|
| 6 |  | 
|---|
| 7 | usage: %prog expression colname < table | 
|---|
| 8 | -H, --header:    keep header in output | 
|---|
| 9 | -C, --comments:  keep comments in output | 
|---|
| 10 | """ | 
|---|
| 11 |  | 
|---|
| 12 | import psyco_full | 
|---|
| 13 |  | 
|---|
| 14 | import sys | 
|---|
| 15 |  | 
|---|
| 16 | import sys | 
|---|
| 17 | import bx.tabular.io | 
|---|
| 18 | from bx.cookbook import doc_optparse | 
|---|
| 19 |  | 
|---|
| 20 | def __main__(): | 
|---|
| 21 |  | 
|---|
| 22 | # Parse command line arguments | 
|---|
| 23 | options, args = doc_optparse.parse( __doc__ ) | 
|---|
| 24 | try: | 
|---|
| 25 | keep_header = bool( options.header ) | 
|---|
| 26 | keep_comments = bool( options.comments ) | 
|---|
| 27 | expr = args[0] | 
|---|
| 28 | colname = args[1] | 
|---|
| 29 | except: | 
|---|
| 30 | doc_optparse.exception() | 
|---|
| 31 |  | 
|---|
| 32 | # Compile expression for SPEED | 
|---|
| 33 | if expr: expr = compile( expr, '<expr arg>', 'eval' ) | 
|---|
| 34 |  | 
|---|
| 35 | for element in bx.tabular.io.Reader( sys.stdin ): | 
|---|
| 36 | if type( element ) is bx.tabular.io.Header: | 
|---|
| 37 | if keep_header: | 
|---|
| 38 | print str( element ) + "\t" + colname | 
|---|
| 39 | elif type( element ) is bx.tabular.io.Comment: | 
|---|
| 40 | if keep_comments: | 
|---|
| 41 | print element | 
|---|
| 42 | else: | 
|---|
| 43 | val = eval( expr, dict( row=element ) ) | 
|---|
| 44 | print str( element ) + "\t" + str( val ) | 
|---|
| 45 |  | 
|---|
| 46 | if __name__ == "__main__": __main__() | 
|---|