Mercurial > hg > sqlex
comparison sqlex/main.py @ 9:834b920ae345 default tip
allow output of headers in csv
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Sat, 01 Apr 2017 15:11:34 -0700 |
parents | adf056d67c01 |
children |
comparison
equal
deleted
inserted
replaced
8:adf056d67c01 | 9:834b920ae345 |
---|---|
40 self.add_argument('--columns', '--list-columns', dest='list_columns', | 40 self.add_argument('--columns', '--list-columns', dest='list_columns', |
41 action='store_true', default=False, | 41 action='store_true', default=False, |
42 help="list columns in `table` and exit") | 42 help="list columns in `table` and exit") |
43 self.add_argument('-o', '--output', | 43 self.add_argument('-o', '--output', |
44 help="output to directory (if `table` not given), or filename or stdout by default") | 44 help="output to directory (if `table` not given), or filename or stdout by default") |
45 self.add_argument('--header', dest='header', | |
46 action='store_true', default=False, | |
47 help="export header as first row") | |
45 self.options = None | 48 self.options = None |
46 | 49 |
47 def parse_args(self, *args, **kw): | 50 def parse_args(self, *args, **kw): |
48 options = argparse.ArgumentParser.parse_args(self, *args, **kw) | 51 options = argparse.ArgumentParser.parse_args(self, *args, **kw) |
49 self.validate(options) | 52 self.validate(options) |
100 if options.table: | 103 if options.table: |
101 # output table | 104 # output table |
102 | 105 |
103 if options.output: | 106 if options.output: |
104 with open(options.output, 'w') as f: | 107 with open(options.output, 'w') as f: |
105 db.table2csv(options.table, f) | 108 db.table2csv(options.table, f, header=options.header) |
106 else: | 109 else: |
107 db.table2csv(options.table, sys.stdout) | 110 db.table2csv(options.table, sys.stdout, header=options.header) |
108 sys.stdout.flush() | 111 sys.stdout.flush() |
109 else: | 112 else: |
110 # output entire db to CSV files in directory | 113 # output entire db to CSV files in directory |
111 | 114 |
112 # ensure directory exists | 115 # ensure directory exists |
114 | 117 |
115 for table in db.tables(): | 118 for table in db.tables(): |
116 # export each table | 119 # export each table |
117 path = os.path.join(options.output, '{}.csv'.format(table)) | 120 path = os.path.join(options.output, '{}.csv'.format(table)) |
118 with open(path, 'w') as f: | 121 with open(path, 'w') as f: |
119 db.table2csv(table, f) | 122 db.table2csv(table, f, header=options.header) |
120 | 123 |
121 | 124 |
122 if __name__ == '__main__': | 125 if __name__ == '__main__': |
123 main() | 126 main() |