Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from tabulate import tabulate
4from .constants import EXIT, DEFAULT_OUTPUT_FORMAT
6# Exports
8__all__ = (
9 "abort",
10 "Row",
11 "Table",
12)
14# Functions
17def abort(code=EXIT.ERROR, message=None):
18 """Stop processing a command line script and optionally issue a message.
20 :param code: The exit code.
21 :type code: int
23 :param message: The message, if any to be displayed.
24 :type message: str
26 """
27 if message is not None:
28 print(message)
30 exit(code)
32# Classes
35class Row(object):
36 """A row in tabular (command line) output."""
38 def __init__(self, number=None, values=None):
39 """Initialize a row.
41 :param number: The row number.
42 :type number: int
44 :param values: The values included in the row.
45 :type values: list
47 """
48 self.number = number
49 self._values = values or list()
51 def __iter__(self):
52 return iter(self._values)
55class Table(object):
56 """A table for tabular (command line) output."""
58 def __init__(self, headings=None, formatting=DEFAULT_OUTPUT_FORMAT, title=None):
59 """Initialize a table.
61 :param headings: A list of headings.
62 :type headings: list[str]
64 :param formatting: The output format of the table.
65 :type formatting: str
67 :param title: The title of the table.
68 :type title: str
70 .. note::
71 Output is generated by python-tabulate. See https://bitbucket.org/astanin/python-tabulate/
73 """
74 self.format = formatting
75 self.headings = headings
76 self.title = title
77 self._rows = list()
79 def __iter__(self):
80 return iter(self._rows)
82 def __str__(self):
83 return self.to_string()
85 def add(self, values):
86 """Add a row to the table.
88 :param values: The values of the row.
89 :type values: list
91 """
92 row = Row(len(self._rows) + 1, values=values)
93 self._rows.append(row)
95 def to_string(self):
96 """Get the table as string output.
98 :rtype: str
100 """
101 output = list()
102 if self.title is not None:
103 output.append("=" * 80)
104 output.append(self.title)
105 output.append("-" * 80)
106 output.append("")
108 table = tabulate(self._rows, headers=self.headings, tablefmt=self.format)
109 output.append(table)
110 output.append("")
112 return "\n".join(output)