view lemuriformes/table2csv.py @ 18:56596902e9ae default tip

add some setup + tests
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:57:03 -0800
parents 4793f99b73e0
children
line wrap: on
line source

#!/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()