Coverage for src/bq_tabulate/tool.py: 57%
21 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-08-08 15:01 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-08-08 15:01 +0200
1"""tool.py -- contains the command line interface to use this package."""
2import argparse
3import json
4import sys
6from tabulate import tabulate
9def bq_tabulate(bq_results, fmt="simple"):
10 """
11 Format results from BQ into pretty-printed text.
13 Format results produced by BigQuery into a text that is pretty-printed in
14 the requested tabulate format `fmt`.
15 """
16 headers = list(bq_results[0].keys())
17 rows = [list(row.values()) for row in bq_results]
18 table = [headers, *rows]
19 return tabulate(table, headers="firstrow", tablefmt=fmt)
22def run():
23 """Run the bqtabulate tool."""
24 args = _parse_cli()
25 bq_json = json.load(args.infile)
26 tabulated = bq_tabulate(bq_json, args.fmt)
27 args.outfile.write(tabulated + "\n")
28 sys.exit(0)
31def _parse_cli():
32 parser = argparse.ArgumentParser(prog="bqtabulate")
33 parser.add_argument(
34 "-i",
35 "--infile",
36 nargs="?",
37 type=argparse.FileType("r"),
38 default=sys.stdin,
39 )
40 parser.add_argument(
41 "-o",
42 "--outfile",
43 nargs="?",
44 type=argparse.FileType("w"),
45 default=sys.stdout,
46 )
47 parser.add_argument("-f", "--fmt", default="simple", help="Table format")
48 return parser.parse_args()