Created
March 30, 2023 21:34
-
-
Save garyellis/3fd0f77df3353c9a06be20e78e44ff9c to your computer and use it in GitHub Desktop.
outputs python utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import csv | |
import json | |
import yaml | |
import logging | |
import tabulate | |
logger = logging.getLogger(__name__) | |
def to_table(items): | |
""" | |
""" | |
print(tabulate.tabulate( | |
tabular_data=items, | |
headers='keys' | |
)) | |
def to_csv(content, filename, append=False, keys=[]): | |
""" | |
""" | |
if content and not keys: | |
keys = content[0].keys() | |
if filename: | |
try: | |
with open(filename, 'w') as stream: | |
csv_writer = csv.DictWriter(stream, keys) | |
except Exception as err: | |
logger.error(err) | |
else: | |
try: | |
csv_writer = csv.DictWriter(sys.stdout, keys) | |
csv_writer.writeheader() | |
csv_writer.writerows(content) | |
except: | |
logger.error(err) | |
def to_yaml(items, filename): | |
""" | |
""" | |
# convert ordered dict to regular dict to bypass adding yaml representer | |
i = json.loads(json.dumps(items)) | |
opts = dict(default_flow_style=False, encoding='utf-8', allow_unicode=True) | |
if not filename: | |
print(yaml.safe_dump(data=i, stream=None, **opts)) | |
else: | |
with open(filename, 'w') as s: | |
yaml.safe_dump(data=i, stream=s, **opts) | |
def to_json(items, filename): | |
""" | |
""" | |
if not filename: | |
print(json.dumps(items)) | |
else: | |
with open(filename, 'w') as s: | |
json.dump(items, filename) | |
def output(items, output_format='table', filename=None): | |
""" | |
""" | |
if output_format == 'table': | |
to_table(items=items) | |
elif output_format == 'json': | |
to_json(items, filename) | |
elif output_format == 'yaml': | |
to_yaml(items, filename) | |
elif output_format == 'csv': | |
if items: | |
to_csv(content=items, filename=filename) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment