Mercurial > hg > Lemuriformes
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemuriformes/table2csv.py Sun Dec 10 17:42:52 2017 -0800 @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +""" +dump a MySQL table to CSV +""" + + +import argparse +import csv +import sys +from .db import MySQLConnection, MySQLParser + + +class MySQLParser(argparse.ArgumentParser): + + def __init__(self, **kwargs): + argparse.ArgumentParser.__init__(self, **kwargs) + self.add_arguments() + self.options = None + + def add_arguments(self): + self.add_argument('host') + self.add_argument('db') + self.add_argument('-u', '--user', dest='user', default='root', + help="MySQL user [DEFAULT: %(default)s]") + self.add_argument('-p', '--password', dest='password', + help="MySQL password [DEFAULT: %(default)s]") + + def parse_args(self, args): + options = argparse.ArgumentParser.parse_args(self, args) + self.options = self.validate(options) + return self.options + + def validate(self, options): + """validate options""" + return options + + def connection(self): + if self.options is None: + raise Exception("parse_args not called successfully!") + + return MySQLConnection(host=self.options.host, + user=self.options.user, + password=self.options.password, + db=self.options.db) + +def main(args=sys.argv[1:]): + + # parse command line + parser = MySQLParser(description=__doc__) + parser.add_argument('table', + help="table to dump") + parser.add_argument('-o', '--output', dest='output', + type=argparse.FileType('w'), default=sys.stdout, + help="path to put data to, or stdout by default") + options = parser.parse_args(args) + + # read table + connection = parser.connection() + data = connection("SELECT * FROM {table}".format(table=options.table)) + + # dump table + writer = csv.writer(options.output) + writer.writerows(data) + options.output.flush() + + +if __name__ == '__main__': + main()