# Imports
from tabulate import tabulate
from .constants import EXIT, DEFAULT_OUTPUT_FORMAT
# Exports
__all__ = (
"abort",
"Row",
"Table",
)
# Functions
[docs]def abort(code=EXIT.ERROR, message=None):
"""Stop processing a command line script and optionally issue a message.
:param code: The exit code.
:type code: int
:param message: The message, if any to be displayed.
:type message: str
"""
if message is not None:
print(message)
exit(code)
# Classes
[docs]class Row(object):
"""A row in tabular (command line) output."""
[docs] def __init__(self, number=None, values=None):
"""Initialize a row.
:param number: The row number.
:type number: int
:param values: The values included in the row.
:type values: list
"""
self.number = number
self._values = values or list()
def __iter__(self):
return iter(self._values)
[docs]class Table(object):
"""A table for tabular (command line) output."""
[docs] def __init__(self, headings=None, formatting=DEFAULT_OUTPUT_FORMAT, title=None):
"""Initialize a table.
:param headings: A list of headings.
:type headings: list[str]
:param formatting: The output format of the table.
:type formatting: str
:param title: The title of the table.
:type title: str
.. note::
Output is generated by python-tabulate. See https://bitbucket.org/astanin/python-tabulate/
"""
self.format = formatting
self.headings = headings
self.title = title
self._rows = list()
def __iter__(self):
return iter(self._rows)
def __str__(self):
return self.to_string()
[docs] def add(self, values):
"""Add a row to the table.
:param values: The values of the row.
:type values: list
"""
row = Row(len(self._rows) + 1, values=values)
self._rows.append(row)
[docs] def to_string(self):
"""Get the table as string output.
:rtype: str
"""
output = list()
if self.title is not None:
output.append("=" * 80)
output.append(self.title)
output.append("-" * 80)
output.append("")
table = tabulate(self._rows, headers=self.headings, tablefmt=self.format)
output.append(table)
output.append("")
return "\n".join(output)