Hide keyboard shortcuts

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 

2 

3from tabulate import tabulate 

4from .constants import EXIT, DEFAULT_OUTPUT_FORMAT 

5 

6# Exports 

7 

8__all__ = ( 

9 "abort", 

10 "Row", 

11 "Table", 

12) 

13 

14# Functions 

15 

16 

17def abort(code=EXIT.ERROR, message=None): 

18 """Stop processing a command line script and optionally issue a message. 

19 

20 :param code: The exit code. 

21 :type code: int 

22 

23 :param message: The message, if any to be displayed. 

24 :type message: str 

25 

26 """ 

27 if message is not None: 

28 print(message) 

29 

30 exit(code) 

31 

32# Classes 

33 

34 

35class Row(object): 

36 """A row in tabular (command line) output.""" 

37 

38 def __init__(self, number=None, values=None): 

39 """Initialize a row. 

40 

41 :param number: The row number. 

42 :type number: int 

43 

44 :param values: The values included in the row. 

45 :type values: list 

46 

47 """ 

48 self.number = number 

49 self._values = values or list() 

50 

51 def __iter__(self): 

52 return iter(self._values) 

53 

54 

55class Table(object): 

56 """A table for tabular (command line) output.""" 

57 

58 def __init__(self, headings=None, formatting=DEFAULT_OUTPUT_FORMAT, title=None): 

59 """Initialize a table. 

60 

61 :param headings: A list of headings. 

62 :type headings: list[str] 

63 

64 :param formatting: The output format of the table. 

65 :type formatting: str 

66 

67 :param title: The title of the table. 

68 :type title: str 

69 

70 .. note:: 

71 Output is generated by python-tabulate. See https://bitbucket.org/astanin/python-tabulate/ 

72 

73 """ 

74 self.format = formatting 

75 self.headings = headings 

76 self.title = title 

77 self._rows = list() 

78 

79 def __iter__(self): 

80 return iter(self._rows) 

81 

82 def __str__(self): 

83 return self.to_string() 

84 

85 def add(self, values): 

86 """Add a row to the table. 

87 

88 :param values: The values of the row. 

89 :type values: list 

90 

91 """ 

92 row = Row(len(self._rows) + 1, values=values) 

93 self._rows.append(row) 

94 

95 def to_string(self): 

96 """Get the table as string output. 

97 

98 :rtype: str 

99 

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("") 

107 

108 table = tabulate(self._rows, headers=self.headings, tablefmt=self.format) 

109 output.append(table) 

110 output.append("") 

111 

112 return "\n".join(output)