comparison lemuriformes/table2csv.py @ 17:4793f99b73e0

[lemuriformes] utility functions
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:42:52 -0800
parents
children
comparison
equal deleted inserted replaced
16:9b1bb9eee962 17:4793f99b73e0
1 #!/usr/bin/env python
2
3 """
4 dump a MySQL table to CSV
5 """
6
7
8 import argparse
9 import csv
10 import sys
11 from .db import MySQLConnection, MySQLParser
12
13
14 class MySQLParser(argparse.ArgumentParser):
15
16 def __init__(self, **kwargs):
17 argparse.ArgumentParser.__init__(self, **kwargs)
18 self.add_arguments()
19 self.options = None
20
21 def add_arguments(self):
22 self.add_argument('host')
23 self.add_argument('db')
24 self.add_argument('-u', '--user', dest='user', default='root',
25 help="MySQL user [DEFAULT: %(default)s]")
26 self.add_argument('-p', '--password', dest='password',
27 help="MySQL password [DEFAULT: %(default)s]")
28
29 def parse_args(self, args):
30 options = argparse.ArgumentParser.parse_args(self, args)
31 self.options = self.validate(options)
32 return self.options
33
34 def validate(self, options):
35 """validate options"""
36 return options
37
38 def connection(self):
39 if self.options is None:
40 raise Exception("parse_args not called successfully!")
41
42 return MySQLConnection(host=self.options.host,
43 user=self.options.user,
44 password=self.options.password,
45 db=self.options.db)
46
47 def main(args=sys.argv[1:]):
48
49 # parse command line
50 parser = MySQLParser(description=__doc__)
51 parser.add_argument('table',
52 help="table to dump")
53 parser.add_argument('-o', '--output', dest='output',
54 type=argparse.FileType('w'), default=sys.stdout,
55 help="path to put data to, or stdout by default")
56 options = parser.parse_args(args)
57
58 # read table
59 connection = parser.connection()
60 data = connection("SELECT * FROM {table}".format(table=options.table))
61
62 # dump table
63 writer = csv.writer(options.output)
64 writer.writerows(data)
65 options.output.flush()
66
67
68 if __name__ == '__main__':
69 main()