Python tabulate.tabulate() Examples
The following are 30
code examples of tabulate.tabulate().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tabulate
, or try the search function
.
Example #1
Source File: console.py From b1tifi with MIT License | 9 votes |
def do_agents(self,args): """ list all agents in interacting """ list_agents = [] # get all session activated if self.settings['agents'].keys() != {}: for agent in self.settings['agents'].keys(): if self.settings['agents'][agent]['tunel'] != None: if self.settings['agents'][agent]['tunel'].activated: list_agents.append([agent,self.settings['agents'][agent]['creds']['Host'], self.settings['agents'][agent]['creds']['Port'], self.settings['agents'][agent]['tunel'].session.name, self.settings['agents'][agent]['tunel'].session.pid]) if list_agents != []: color.display_messages('Session Agents:', info=True, sublime=True) print tabulate(list_agents,headers=C.headersAgents) color.linefeed() return color.display_messages('Online Agents: {}'.format(color.setcolor(str(len(list_agents)), color='blue')), info=True) color.display_messages('No agents in interacting', info=True)
Example #2
Source File: gftools-list-weightclass.py From gftools with Apache License 2.0 | 8 votes |
def main(): args = parser.parse_args() headers = ['filename', 'usWeightClass'] rows = [] for font in args.font: ttfont = ttLib.TTFont(font) rows.append([os.path.basename(font), ttfont['OS/2'].usWeightClass]) def as_csv(rows): import csv import sys writer = csv.writer(sys.stdout) writer.writerows([headers]) writer.writerows(rows) sys.exit(0) if args.csv: as_csv(rows) print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
Example #3
Source File: gftools-fix-fsselection.py From gftools with Apache License 2.0 | 7 votes |
def printInfo(fonts, print_csv=False): rows = [] headers = ['filename', 'fsSelection'] for font in fonts: ttfont = ttLib.TTFont(font) row = [os.path.basename(font)] row.append(('{:#010b} ' '{:#010b}' '').format(getByte2(ttfont), getByte1(ttfont)).replace('0b', '')) rows.append(row) def as_csv(rows): writer = csv.writer(sys.stdout) writer.writerows([headers]) writer.writerows(rows) sys.exit(0) if print_csv: as_csv(rows) else: print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
Example #4
Source File: gftools-list-widthclass.py From gftools with Apache License 2.0 | 7 votes |
def print_info(fonts, print_csv=False): headers = ['filename', 'usWidthClass'] rows = [] warnings = [] for font in fonts: ttfont = ttLib.TTFont(font) usWidthClass = ttfont['OS/2'].usWidthClass rows.append([os.path.basename(font), usWidthClass]) if usWidthClass != 5: warning = "WARNING: {} is {}, expected 5" warnings.append(warning.format(font, usWidthClass)) def as_csv(rows): writer = csv.writer(sys.stdout) writer.writerows([headers]) writer.writerows(rows) sys.exit(0) if print_csv: as_csv(rows) print(tabulate.tabulate(rows, headers, tablefmt="pipe")) for warn in warnings: print(warn, file=sys.stderr)
Example #5
Source File: run.py From floyd-cli with Apache License 2.0 | 6 votes |
def validate_env(env, arch): env_map = EnvClient().get_all() envs = env_map.get(arch) if envs: if env not in envs: envlist = tabulate([ [env_name] for env_name in sorted(envs.keys()) ]) floyd_logger.error("%s is not in the list of supported environments:\n%s", env, envlist) return False else: floyd_logger.error("invalid instance type") return False return True
Example #6
Source File: findingformatterfactory.py From securityheaders with Apache License 2.0 | 6 votes |
def format(self, findings): table = [] for finding in findings: url = str(finding.url) if finding.url else '' severity = str(finding.severity.name) if finding.severity.name else '' header = str(finding.header) if finding.header else "" ftype = str(finding.ftype.name.lower()) if finding.ftype.name else "" directive = str(finding.directive) if finding.directive else "" value = str(finding.value) if finding.value else "" description = str(finding.description) if finding.description else "" f = finding if self.hascolor: color = self.getColor(finding.severity) endColor = '\033[0m' else: color = '' endColor = '' table.append([url, color + severity + endColor +"", header, ftype, directive, value, description]) return str(tabulate(table, headers=["URL","Severity", "Header", "Finding Type", "Directive", "Value","Description"],tablefmt=self.tableformat))
Example #7
Source File: test_output.py From python-tabulate with MIT License | 6 votes |
def test_plain_multiline_with_empty_cells(): "Output: plain with multiline cells and empty cells with headers" table = [ ["hdr", "data", "fold"], ["1", "", ""], ["2", "very long data", "fold\nthis"], ] expected = "\n".join( [ " hdr data fold", " 1", " 2 very long data fold", " this", ] ) result = tabulate(table, headers="firstrow", tablefmt="plain") assert_equal(expected, result)
Example #8
Source File: gftools-list-widthclass.py From gftools with Apache License 2.0 | 6 votes |
def fix(fonts, value=None): rows = [] headers = ['filename', 'usWidthClass was', 'usWidthClass now'] for font in fonts: row = [font] ttfont = ttLib.TTFont(font) if not value: usWidthClass = getFromFilename(font) else: usWidthClass = value row.append(ttfont['OS/2'].usWidthClass) ttfont['OS/2'].usWidthClass = usWidthClass row.append(ttfont['OS/2'].usWidthClass) ttfont.save(font + '.fix') rows.append(row) if rows: print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
Example #9
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_sqlite3_keys(): "Input: an sqlite3 cursor with keys as headers" try: import sqlite3 conn = sqlite3.connect(":memory:") cursor = conn.cursor() cursor.execute("CREATE TABLE people (name, age, height)") for values in [("Alice", 23, 169.5), ("Bob", 27, 175.0)]: cursor.execute("INSERT INTO people VALUES (?, ?, ?)", values) cursor.execute( 'SELECT name "whom", age "how old", height "how tall" FROM people ORDER BY name' ) result = tabulate(cursor, headers="keys") expected = """\ whom how old how tall ------ --------- ---------- Alice 23 169.5 Bob 27 175""" assert_equal(expected, result) except ImportError: skip("test_sqlite3_keys is skipped")
Example #10
Source File: etcd.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def list_images(cli_ctx, short, installed): '''List all configured images.''' async def _impl(): async with config_ctx(cli_ctx) as config_server: displayed_items = [] try: items = await config_server.list_images() for item in items: if installed and not item['installed']: continue if short: img = ImageRef(f"{item['name']}:{item['tag']}", item['registry']) displayed_items.append((img.canonical, item['digest'])) else: pprint(item) if short: print(tabulate(displayed_items, tablefmt='plain')) except Exception: log.exception('An error occurred.') with cli_ctx.logger: asyncio.run(_impl())
Example #11
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_numpy_record_array_headers(): "Input: a 2D NumPy record array with user-supplied headers." try: import numpy na = numpy.asarray( [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], "formats": ["a32", "uint8", "float32"], }, ) expected = "\n".join( [ "person years cm", "-------- ------- -----", "Alice 23 169.5", "Bob 27 175", ] ) result = tabulate(na, headers=["person", "years", "cm"]) assert_equal(expected, result) except ImportError: skip("test_numpy_2d_keys is skipped")
Example #12
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_numpy_record_array_keys(): "Input: a 2D NumPy record array with column names as headers." try: import numpy na = numpy.asarray( [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], "formats": ["a32", "uint8", "float32"], }, ) expected = "\n".join( [ "name age height", "------ ----- --------", "Alice 23 169.5", "Bob 27 175", ] ) result = tabulate(na, headers="keys") assert_equal(expected, result) except ImportError: skip("test_numpy_2d_keys is skipped")
Example #13
Source File: eval_zoo.py From c3dpo_nrsfm with MIT License | 6 votes |
def print_results_per_class(avg_cls_results, all_avg_results): metrics = list(all_avg_results.keys()) # result printing avg_results_print = copy.deepcopy(avg_cls_results) avg_results_print['== Mean =='] = all_avg_results tab_rows = [] for cls_, cls_metrics in avg_results_print.items(): tab_row = [cls_] for metric in metrics: val = cls_metrics[metric] tab_row.append("%1.3f" % val) tab_rows.append(tab_row) headers = ['classes'] headers.extend(copy.deepcopy(metrics)) print(tabulate(tab_rows, headers=headers))
Example #14
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_numpy_record_array(): "Input: a 2D NumPy record array without header." try: import numpy na = numpy.asarray( [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], "formats": ["a32", "uint8", "float32"], }, ) expected = "\n".join( [ "----- -- -----", "Alice 23 169.5", "Bob 27 175", "----- -- -----", ] ) result = tabulate(na) assert_equal(expected, result) except ImportError: skip("test_numpy_2d_keys is skipped")
Example #15
Source File: heist.py From discord_cogs with GNU General Public License v3.0 | 6 votes |
def _targets_heist(self, ctx): """Shows a list of targets""" guild = ctx.guild theme = await self.thief.get_guild_theme(guild) targets = await self.thief.get_guild_targets(guild) t_vault = theme["Vault"] if len(targets.keys()) < 0: msg = ("There aren't any targets! To create a target use {}heist " "createtarget .".format(ctx.prefix)) else: target_names = [x for x in targets] crews = [int(subdict["Crew"]) for subdict in targets.values()] success = [str(subdict["Success"]) + "%" for subdict in targets.values()] vaults = [subdict["Vault"] for subdict in targets.values()] data = list(zip(target_names, crews, vaults, success)) table_data = sorted(data, key=itemgetter(1), reverse=True) table = tabulate(table_data, headers=["Target", "Max Crew", t_vault, "Success Rate"]) msg = "```C\n{}```".format(table) await ctx.send(msg)
Example #16
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_numpy_2d(): "Input: a 2D NumPy array with headers." try: import numpy na = (numpy.arange(1, 10, dtype=numpy.float32).reshape((3, 3)) ** 3) * 0.5 expected = "\n".join( [ " a b c", "----- ----- -----", " 0.5 4 13.5", " 32 62.5 108", "171.5 256 364.5", ] ) result = tabulate(na, ["a", "b", "c"]) assert_equal(expected, result) except ImportError: skip("test_numpy_2d is skipped")
Example #17
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_pandas(): "Input: a Pandas DataFrame." try: import pandas df = pandas.DataFrame([["one", 1], ["two", None]], index=["a", "b"]) expected = "\n".join( [ " string number", "-- -------- --------", "a one 1", "b two nan", ] ) result = tabulate(df, headers=["string", "number"]) assert_equal(expected, result) except ImportError: skip("test_pandas is skipped")
Example #18
Source File: experiment.py From floyd-cli with Apache License 2.0 | 6 votes |
def info(job_name_or_id): """ View detailed information of a job. """ try: experiment = ExperimentClient().get(normalize_job_name(job_name_or_id)) except FloydException: experiment = ExperimentClient().get(job_name_or_id) task_instance_id = get_module_task_instance_id(experiment.task_instances) task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None normalized_job_name = normalize_job_name(experiment.name) table = [["Job name", normalized_job_name], ["Created", experiment.created_pretty], ["Status", experiment.state], ["Duration(s)", experiment.duration_rounded], ["Instance", experiment.instance_type_trimmed], ["Description", experiment.description], ["Metrics", format_metrics(experiment.latest_metrics)]] if task_instance and task_instance.mode in ['jupyter', 'serving']: table.append(["Mode", task_instance.mode]) table.append(["Url", experiment.service_url]) if experiment.tensorboard_url: table.append(["TensorBoard", experiment.tensorboard_url]) floyd_logger.info(tabulate(table))
Example #19
Source File: test_input.py From python-tabulate with MIT License | 6 votes |
def test_sqlite3(): "Input: an sqlite3 cursor" try: import sqlite3 conn = sqlite3.connect(":memory:") cursor = conn.cursor() cursor.execute("CREATE TABLE people (name, age, height)") for values in [("Alice", 23, 169.5), ("Bob", 27, 175.0)]: cursor.execute("INSERT INTO people VALUES (?, ?, ?)", values) cursor.execute("SELECT name, age, height FROM people ORDER BY name") result = tabulate(cursor, headers=["whom", "how old", "how tall"]) expected = """\ whom how old how tall ------ --------- ---------- Alice 23 169.5 Bob 27 175""" assert_equal(expected, result) except ImportError: skip("test_sqlite3 is skipped")
Example #20
Source File: test_output.py From python-tabulate with MIT License | 5 votes |
def test_plain_multiline(): "Output: plain with multiline cells with headers" table = [[2, "foo\nbar"]] headers = ("more\nspam \x1b[31meggs\x1b[0m", "more spam\n& eggs") expected = "\n".join( [ " more more spam", " spam \x1b[31meggs\x1b[0m & eggs", " 2 foo", " bar", ] ) result = tabulate(table, headers, tablefmt="plain") assert_equal(expected, result)
Example #21
Source File: experiment.py From floyd-cli with Apache License 2.0 | 5 votes |
def print_experiments(experiments): """ Prints job details in a table. Includes urls and mode parameters """ headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"] expt_list = [] for experiment in experiments: expt_list.append([normalize_job_name(experiment.name), experiment.created_pretty, experiment.state, experiment.duration_rounded, experiment.instance_type_trimmed, experiment.description, format_metrics(experiment.latest_metrics)]) floyd_logger.info(tabulate(expt_list, headers=headers))
Example #22
Source File: data.py From floyd-cli with Apache License 2.0 | 5 votes |
def print_data(data_sources): """ Print dataset information in tabular form """ if not data_sources: return headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"] data_list = [] for data_source in data_sources: data_list.append([data_source.name, data_source.created_pretty, data_source.state, data_source.size]) floyd_logger.info(tabulate(data_list, headers=headers))
Example #23
Source File: test_output.py From python-tabulate with MIT License | 5 votes |
def test_simple_multiline_2(): "Output: simple with multiline cells" expected = "\n".join( [ " key value", "----- ---------", " foo bar", "spam multiline", " world", ] ) table = [["key", "value"], ["foo", "bar"], ["spam", "multiline\nworld"]] result = tabulate(table, headers="firstrow", stralign="center", tablefmt="simple") assert_equal(expected, result)
Example #24
Source File: test_output.py From python-tabulate with MIT License | 5 votes |
def test_plain_multiline_with_empty_cells_headerless(): "Output: plain with multiline cells and empty cells without headers" table = [["0", "", ""], ["1", "", ""], ["2", "very long data", "fold\nthis"]] expected = "\n".join( ["0", "1", "2 very long data fold", " this"] ) result = tabulate(table, tablefmt="plain") assert_equal(expected, result)
Example #25
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_iterable_of_iterables_headers(): "Input: an interable of iterables with headers." ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) expected = "\n".join( [ " a b c d e", "--- --- --- --- ---", " 0 1 2 3 4", " 5 4 3 2 1", ] ) result = tabulate(ii, "abcde") assert_equal(expected, result)
Example #26
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_iterable_of_iterables_firstrow(): "Input: an interable of iterables with the first row as headers" ii = iter(map(lambda x: iter(x), ["abcde", range(5), range(5, 0, -1)])) expected = "\n".join( [ " a b c d e", "--- --- --- --- ---", " 0 1 2 3 4", " 5 4 3 2 1", ] ) result = tabulate(ii, "firstrow") assert_equal(expected, result)
Example #27
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_list_of_lists_firstrow(): "Input: a list of lists with the first row as headers." ll = [["string", "number"], ["a", "one", 1], ["b", "two", None]] expected = "\n".join( [ " string number", "-- -------- --------", "a one 1", "b two", ] ) result = tabulate(ll, headers="firstrow") assert_equal(expected, result)
Example #28
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_list_of_lists_keys(): "Input: a list of lists with column indices as headers." ll = [["a", "one", 1], ["b", "two", None]] expected = "\n".join( ["0 1 2", "--- --- ---", "a one 1", "b two"] ) result = tabulate(ll, headers="keys") assert_equal(expected, result)
Example #29
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_dict_like(): "Input: a dict of iterables with keys as headers." # columns should be padded with None, keys should be used as headers dd = {"a": range(3), "b": range(101, 105)} # keys' order (hence columns' order) is not deterministic in Python 3 # => we have to consider both possible results as valid expected1 = "\n".join( [" a b", "--- ---", " 0 101", " 1 102", " 2 103", " 104"] ) expected2 = "\n".join( [" b a", "--- ---", "101 0", "102 1", "103 2", "104"] ) result = tabulate(dd, "keys") print("Keys' order: %s" % dd.keys()) assert_in(result, [expected1, expected2])
Example #30
Source File: test_input.py From python-tabulate with MIT License | 5 votes |
def test_iterable_of_iterables(): "Input: an interable of iterables." ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) expected = "\n".join( ["- - - - -", "0 1 2 3 4", "5 4 3 2 1", "- - - - -"] ) result = tabulate(ii) assert_equal(expected, result)