diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-06-26 00:34:50 -0700 |
---|---|---|
committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-06-26 00:34:50 -0700 |
commit | 8e49e5a0b4b21f70740e025a40e4ac0f6d573c4d (patch) | |
tree | f7aaf3eabe86c4839adb3b26ac94a72d2f26742e | |
parent | 63aa28c284a9c854b950f4bf2dbe4aa438f21365 (diff) | |
download | cmd2-git-8e49e5a0b4b21f70740e025a40e4ac0f6d573c4d.tar.gz |
table_display.py example now uses tableformatter instead of tabulate
Changed the table_display.py example to use the tableformatter module which resuls in nicer looking tables.
-rwxr-xr-x | examples/table_display.py | 77 |
1 files changed, 60 insertions, 17 deletions
diff --git a/examples/table_display.py b/examples/table_display.py index 2e6ea804..c81b6751 100755 --- a/examples/table_display.py +++ b/examples/table_display.py @@ -1,36 +1,78 @@ #!/usr/bin/env python # coding=utf-8 """A simple example demonstrating the following: - 1) How to display tabular data within a cmd2 application + 1) How to display tabular data 2) How to display output using a pager NOTE: IF the table does not entirely fit within the screen of your terminal, then it will be displayed using a pager. You can use the arrow keys (left, right, up, and down) to scroll around the table as well as the PageUp/PageDown keys. You can quit out of the pager by typing "q". You can also search for text within the pager using "/". -WARNING: This example requires the tabulate module. +WARNING: This example requires the tableformatter module: https://github.com/python-tableformatter/tableformatter +- pip install tableformatter """ import functools import cmd2 -import tabulate +import tableformatter as tf -# Format to use with tabulate module when displaying tables -TABLE_FORMAT = 'grid' +try: + from colored import bg + BACK_PRI = bg(4) + BACK_ALT = bg(2) +except ImportError: + try: + from colorama import Back + BACK_PRI = Back.LIGHTBLUE_EX + BACK_ALT = Back.LIGHTYELLOW_EX + except ImportError: + BACK_PRI = '' + BACK_ALT = '' + +# Format to use for the grid style when displaying tables with the tableformatter module +grid_style = tf.AlternatingRowGrid(BACK_PRI, BACK_ALT) # Use rows of alternating color to assist as a visual guide # Create a function to format a fixed-width table for pretty-printing using the desired table format -table = functools.partial(tabulate.tabulate, tablefmt=TABLE_FORMAT) +table = functools.partial(tf.generate_table, grid_style=grid_style) + # Population data from Wikipedia: https://en.wikipedia.org/wiki/List_of_cities_proper_by_population -EXAMPLE_DATA = [['Shanghai', 'Shanghai', 'China', 'Asia', 24183300, 6340.5, 3814], - ['Beijing', 'Hebei', 'China', 'Asia', 20794000, 1749.57, 11885], - ['Karachi', 'Sindh', 'Pakistan', 'Asia', 14910352, 615.58, 224221], - ['Shenzen', 'Guangdong', 'China', 'Asia', 13723000, 1493.32, 9190], - ['Guangzho', 'Guangdong', 'China', 'Asia', 13081000, 1347.81, 9705], - ['Mumbai', ' Maharashtra', 'India', 'Asia', 12442373, 465.78, 27223], - ['Istanbul', 'Istanbul', 'Turkey', 'Eurasia', 12661000, 620.29, 20411], +EXAMPLE_DATA = [['Shanghai', 'Shanghai', 'China', 'Asia', 24183300, 6340.5], + ['Beijing', 'Hebei', 'China', 'Asia', 20794000, 1749.57], + ['Karachi', 'Sindh', 'Pakistan', 'Asia', 14910352, 615.58], + ['Shenzen', 'Guangdong', 'China', 'Asia', 13723000, 1493.32], + ['Guangzho', 'Guangdong', 'China', 'Asia', 13081000, 1347.81], + ['Mumbai', 'Maharashtra', 'India', 'Asia', 12442373, 465.78], + ['Istanbul', 'Istanbul', 'Turkey', 'Eurasia', 12661000, 620.29], ] -EXAMPLE_HEADERS = ['City', 'Province', 'Country', 'Continent', 'Population', 'Area (km^2)', 'Pop. Density (/km^2)'] + +# Calculate population density +for row in EXAMPLE_DATA: + row.append(row[-2]/row[-1]) + + +# TODO: Color row text foreground based on population density + + +def no_dec(num: float) -> str: + """Format a floating point number with no decimal places.""" + return "{}".format(round(num)) + + +def two_dec(num: float) -> str: + """Format a floating point number with 2 decimal places.""" + return "{0:.2f}".format(num) + + +# # Column headers plus optional formatting info for each column +columns = [tf.Column('City', header_halign=tf.ColumnAlignment.AlignCenter), + tf.Column('Province', header_halign=tf.ColumnAlignment.AlignCenter), + 'Country', # NOTE: If you don't need any special effects, you can just pass a string + tf.Column('Continent', cell_halign=tf.ColumnAlignment.AlignCenter), + tf.Column('Population', cell_halign=tf.ColumnAlignment.AlignRight, formatter=tf.FormatCommas()), + tf.Column('Area (km^2)', cell_halign=tf.ColumnAlignment.AlignRight, formatter=two_dec), + tf.Column('Pop. Density (/km^2)', width=12, cell_halign=tf.ColumnAlignment.AlignRight, formatter=no_dec), + ] class TableDisplay(cmd2.Cmd): @@ -51,14 +93,15 @@ class TableDisplay(cmd2.Cmd): - if `headers="keys"`, then dictionary keys or column indices are used - Otherwise, a headerless table is produced """ - formatted_table = table(tabular_data, headers=headers) - self.ppaged(formatted_table) + formatted_table = table(rows=tabular_data, columns=headers) + self.ppaged(formatted_table, chop=True) def do_table(self, _): """Display data on the Earth's most populated cities in a table.""" - self.ptable(tabular_data=EXAMPLE_DATA, headers=EXAMPLE_HEADERS) + self.ptable(EXAMPLE_DATA, columns) if __name__ == '__main__': app = TableDisplay() + app.debug = True app.cmdloop() |