export_csv 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env vpython3
  2. # Copyright 2018 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import argparse
  6. import contextlib
  7. import csv
  8. import os
  9. import sqlite3
  10. import sys
  11. DEFAULT_DATABASE_PATH = os.path.abspath(os.path.join(
  12. os.path.dirname(__file__), '_cached_data', 'soundwave', 'soundwave.db'))
  13. @contextlib.contextmanager
  14. def OutputStream(filename):
  15. if filename is None or filename == '-':
  16. yield sys.stdout
  17. else:
  18. with open(filename, 'w') as f:
  19. yield f
  20. def EncodeUnicode(v):
  21. return v.encode('utf-8') if isinstance(v, unicode) else v
  22. def main():
  23. parser = argparse.ArgumentParser()
  24. parser.add_argument(
  25. 'table', help='Name of a table to export')
  26. parser.add_argument(
  27. '--database-file', default=DEFAULT_DATABASE_PATH,
  28. help='File path for database where to store data.')
  29. parser.add_argument(
  30. '--output', '-o',
  31. help='Where to write the csv output, defaults to stdout.')
  32. args = parser.parse_args()
  33. con = sqlite3.connect(args.database_file)
  34. try:
  35. cur = con.execute('SELECT * FROM %s' % args.table)
  36. header = [c[0] for c in cur.description]
  37. with OutputStream(args.output) as out:
  38. writer = csv.writer(out)
  39. writer.writerow(header)
  40. for row in cur:
  41. writer.writerow([EncodeUnicode(v) for v in row])
  42. finally:
  43. con.close()
  44. if __name__ == '__main__':
  45. sys.exit(main())