Python prettytable.ALL Examples

The following are 21 code examples of prettytable.ALL(). 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 prettytable , or try the search function .
Example #1
Source File: status.py    From kuryr-kubernetes with Apache License 2.0 6 votes vote down vote up
def upgrade_check(self):
        check_results = []

        t = prettytable.PrettyTable(['Upgrade Check Results'],
                                    hrules=prettytable.ALL)
        t.align = 'l'

        for name, method in self.check_methods.items():
            result = method()
            check_results.append(result)
            cell = (
                'Check: %(name)s\n'
                'Result: %(result)s\n'
                'Details: %(details)s' %
                {
                    'name': name,
                    'result': UPGRADE_CHECK_MSG_MAP[result.code],
                    'details': result.get_details(),
                }
            )
            t.add_row([cell])
        print(t)

        return max(res.code for res in check_results) 
Example #2
Source File: utils.py    From anchore-cli with Apache License 2.0 6 votes vote down vote up
def _format_gates(payload, all=False):
    if not all:
        header = ['Gate', 'Description']
    else:
        header = ['Gate', 'Description', 'State', 'Superceded By']

    t = PrettyTable(header, hrules=ALL)
    t.align = 'l'

    if payload:
        for gate in payload:
            desc = string_splitter(gate.get('description', ''), 60)
            if all:
                t.add_row([gate['name'].lower(), desc, gate.get('state', ''), gate.get('superceded_by', '')])
            elif gate.get('state') in [None, 'active']:
                t.add_row([gate['name'].lower(), desc])

        return t.get_string(sortby='Gate', print_empty=True)
    else:
        return  'No policy spec to parse' 
Example #3
Source File: utils.py    From anchore-cli with Apache License 2.0 6 votes vote down vote up
def _format_triggers(payload, gate, all=False):
    if not all:
        header = ['Trigger', 'Description', 'Parameters']
    else:
        header = ['Trigger', 'Description', 'Parameters', 'State', 'Superceded By']
    t = PrettyTable(header, hrules=ALL)
    t.align = 'l'

    if payload:
        for gate in [x for x in payload if x['name'].lower() == gate]:
            for trigger_entry in gate.get('triggers', []):
                desc = string_splitter(trigger_entry.get('description', ''))
                param_str = string_splitter(', '.join([x['name'].lower() for x in trigger_entry.get('parameters', [])]), max_length=20)
                if all:
                    t.add_row([trigger_entry['name'].lower(), desc, param_str, trigger_entry.get('state', ''), trigger_entry.get('superceded_by', '')])
                elif trigger_entry.get('state') in [None, 'active']:
                    t.add_row([trigger_entry['name'].lower(), desc, param_str])

        return t.get_string(sortby='Trigger', print_empty=True)
    else:
        return 'No policy spec to parse' 
Example #4
Source File: utils.py    From anchore-cli with Apache License 2.0 6 votes vote down vote up
def _format_trigger_params(payload, gate, trigger, all=False):
    if all:
        header = ['Parameter', 'Description', 'Required', 'Example', 'State', 'Supereceded By']
    else:
        header = ['Parameter', 'Description', 'Required', 'Example']
    t = PrettyTable(header, hrules=ALL)
    t.align = 'l'

    if payload:
        for gate in [x for x in payload if x['name'].lower() == gate]:
            for trigger_entry in [x for x in gate.get('triggers', []) if x['name'].lower() == trigger]:
                for p in trigger_entry.get('parameters', []):
                    desc = string_splitter(p.get('description', ''))
                    if all:
                        t.add_row([p['name'].lower(), desc, p.get('required', True), p.get('example',''), p.get('state', ''), p.get('superceded_by', '')])
                    elif p.get('state') in [None, 'active']:
                        t.add_row([p['name'].lower(), desc, p.get('required', True), p.get('example', '')])


        return t.get_string(sortby='Parameter', print_empty=True)
    else:
        return 'No policy spec to parse' 
Example #5
Source File: plain.py    From kube-hunter with Apache License 2.0 6 votes vote down vote up
def nodes_table(self):
        nodes_table = PrettyTable(["Type", "Location"], hrules=ALL)
        nodes_table.align = "l"
        nodes_table.max_width = MAX_TABLE_WIDTH
        nodes_table.padding_width = 1
        nodes_table.sortby = "Type"
        nodes_table.reversesort = True
        nodes_table.header_style = "upper"
        id_memory = set()
        services_lock.acquire()
        for service in services:
            if service.event_id not in id_memory:
                nodes_table.add_row(["Node/Master", service.host])
                id_memory.add(service.event_id)
        nodes_ret = "\nNodes\n{}\n".format(nodes_table)
        services_lock.release()
        return nodes_ret 
Example #6
Source File: rendering.py    From kaos with Apache License 2.0 6 votes vote down vote up
def render_table(data, header=None, include_ind=True, drop_cols: set = None):
    if not drop_cols:
        drop_cols = set()

    for d in data:
        for k in list(d):
            if k in drop_cols:
                del d[k]

    # set up simple table to iterate through response
    table = PrettyTable(hrules=prettytable.ALL)
    if header:
        table.title = header
    out = list(data)

    if include_ind:
        table.field_names = ['ind'] + list(out[0].keys())
        for ind, d in enumerate(out):
            table.add_row([ind] + list(d.values()))
    else:
        table.field_names = list(out[0].keys())
        for d in out:
            table.add_row(list(d.values()))
    return table.get_string() 
Example #7
Source File: dns_cnc_srv.py    From pacdoor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _mk_tbl(fields):
    tbl = prettytable.PrettyTable(fields, left_padding_width=1, right_padding_width=1, hrules=prettytable.ALL)
    col_max_width = (terminalsize()[0] / len(fields)) - 5

    for k in tbl.align:
        tbl.align[k] = 'l'

    return (tbl, col_max_width) 
Example #8
Source File: driver.py    From ibis with Apache License 2.0 5 votes vote down vote up
def _print_table_wf_map(self):
        """Prints readable table"""
        print_obj = prettytable.PrettyTable([
            'Source Tables', 'Views - Hive Tables', 'Full Load Workflow',
            'Incremental Workflow', 'Grouped Workflow'])
        print_obj.hrules = prettytable.ALL
        print_obj.max_width = 80
        print_obj.sortby = 'Full Load Workflow'
        for each in self.table_workflows.values():
            print_obj.add_row([each.table_id, each.view_table_names,
                               each.full_wf, each.incr_wf, each.is_subwf_wf])
        msg = 'Caution: Run full load workflow prior to incremental workflow'
        self.logger.info('\n\n' + msg + '\n' + print_obj.get_string() + '\n') 
Example #9
Source File: plain.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def hunters_table(self):
        column_names = ["Name", "Description", "Vulnerabilities"]
        hunters_table = PrettyTable(column_names, hrules=ALL)
        hunters_table.align = "l"
        hunters_table.max_width = MAX_TABLE_WIDTH
        hunters_table.sortby = "Name"
        hunters_table.reversesort = True
        hunters_table.padding_width = 1
        hunters_table.header_style = "upper"

        hunter_statistics = self.get_hunter_statistics()
        for item in hunter_statistics:
            hunters_table.add_row([item.get("name"), item.get("description"), item.get("vulnerabilities")])
        return f"\nHunter Statistics\n{hunters_table}\n" 
Example #10
Source File: plain.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def vulns_table(self):
        column_names = [
            "ID",
            "Location",
            "Category",
            "Vulnerability",
            "Description",
            "Evidence",
        ]
        vuln_table = PrettyTable(column_names, hrules=ALL)
        vuln_table.align = "l"
        vuln_table.max_width = MAX_TABLE_WIDTH
        vuln_table.sortby = "Category"
        vuln_table.reversesort = True
        vuln_table.padding_width = 1
        vuln_table.header_style = "upper"

        with vulnerabilities_lock:
            for vuln in vulnerabilities:
                evidence = str(vuln.evidence)
                if len(evidence) > EVIDENCE_PREVIEW:
                    evidence = evidence[:EVIDENCE_PREVIEW] + "..."
                row = [
                    vuln.get_vid(),
                    vuln.location(),
                    vuln.category.name,
                    vuln.get_name(),
                    vuln.explain(),
                    evidence,
                ]
                vuln_table.add_row(row)
        return (
            "\nVulnerabilities\n"
            "For further information about a vulnerability, search its ID in: \n"
            f"{KB_LINK}\n{vuln_table}\n"
        ) 
Example #11
Source File: plain.py    From kube-hunter with Apache License 2.0 5 votes vote down vote up
def services_table(self):
        services_table = PrettyTable(["Service", "Location", "Description"], hrules=ALL)
        services_table.align = "l"
        services_table.max_width = MAX_TABLE_WIDTH
        services_table.padding_width = 1
        services_table.sortby = "Service"
        services_table.reversesort = True
        services_table.header_style = "upper"
        with services_lock:
            for service in services:
                services_table.add_row(
                    [service.get_name(), f"{service.host}:{service.port}{service.get_path()}", service.explain()]
                )
            detected_services_ret = f"\nDetected Services\n{services_table}\n"
        return detected_services_ret 
Example #12
Source File: firepwned.py    From firepwned with GNU General Public License v3.0 5 votes vote down vote up
def display_results(saved_credentials, pwned_passwords):
    
    if len(pwned_passwords) == 0:
        LOG.info("Good news - it looks like none of your Firefox saved password is pwned!")
        return

    table = prettytable.PrettyTable([
        COLOR_BOLD + 'Website' + COLOR_RESET,
        COLOR_BOLD + 'Username' + COLOR_RESET,
        COLOR_BOLD + 'Password' + COLOR_RESET,
        COLOR_BOLD + 'Status' + COLOR_RESET
    ], hrules=prettytable.ALL)

    for credential in saved_credentials:
        password = credential['password']
        if password in pwned_passwords:
            count = pwned_passwords[password]
            message = 'Pwned in %d breaches!' % count
            table.add_row([
                credential['url'],
                credential['username'],
                password,
                COLOR_RED + COLOR_BOLD + message + COLOR_RESET
            ])
    
    print(table) 
Example #13
Source File: rendering.py    From kaos with Apache License 2.0 5 votes vote down vote up
def render_job_info(data, sort_by):
    response = PagedResponse.from_dict(data)
    info = JobInfo.from_dict(response.response)
    page_id = response.page_id
    page_count = response.page_count
    # "global" (i.e. job) level info
    formatted_info = f"""
    Job ID: {info.job_id}
    Process time: {info.process_time}
    State: {info.state}
    Available metrics: {info.available_metrics}

    Page count: {page_count}
    Page ID: {page_id}"""
    table = PrettyTable(hrules=prettytable.ALL)
    header = ['ind', 'Code', 'Data', 'Model ID', 'Hyperparams']
    if sort_by:
        header.append('Score')
    table.field_names = header
    for ind, d in enumerate(info.partitions):
        code = d.code
        code_summary = f"Author: {code.author}\nPath: {code.path}"

        data = d.data
        data_summary = f"Author: {data.author}\nPath: {data.path}"

        hyper_summary = None
        if d.hyperparams:
            hyper = d.hyperparams
            hyper_summary = f"Author: {hyper.author}\nPath: {hyper.path}"

        output = d.output
        output_summary = f"{output.path}"
        row = [ind, code_summary, data_summary, output_summary, hyper_summary]
        if sort_by:
            row.append(d.score)
        table.add_row(row)
    formatted_info += "\n" + table.get_string()
    return formatted_info 
Example #14
Source File: ctl.py    From patroni with MIT License 5 votes vote down vote up
def print_output(columns, rows, alignment=None, fmt='pretty', header=None, delimiter='\t'):
    if fmt in {'json', 'yaml', 'yml'}:
        elements = [{k: v for k, v in zip(columns, r) if not header or str(v)} for r in rows]
        func = json.dumps if fmt == 'json' else format_config_for_editing
        click.echo(func(elements))
    elif fmt in {'pretty', 'tsv', 'topology'}:
        list_cluster = bool(header and columns and columns[0] == 'Cluster')
        if list_cluster and 'Tags' in columns:  # we want to format member tags as YAML
            i = columns.index('Tags')
            for row in rows:
                if row[i]:
                    row[i] = format_config_for_editing(row[i], fmt != 'pretty').strip()
        if list_cluster and fmt != 'tsv':  # skip cluster name if pretty-printing
            columns = columns[1:] if columns else []
            rows = [row[1:] for row in rows]

        if fmt == 'tsv':
            for r in ([columns] if columns else []) + rows:
                click.echo(delimiter.join(map(str, r)))
        else:
            hrules = ALL if any(any(isinstance(c, six.string_types) and '\n' in c for c in r) for r in rows) else FRAME
            table = PatronictlPrettyTable(header, columns, hrules=hrules)
            for k, v in (alignment or {}).items():
                table.align[k] = v
            for r in rows:
                table.add_row(r)
            click.echo(table) 
Example #15
Source File: document_callback.py    From ansible-baseline with GNU General Public License v3.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('module', nargs='?',
                        default='callback_plugins.baseline')
    parser.add_argument('--rst', action='store_true')
    args = parser.parse_args()

    if args.rst:
        br = '\n| '
        start = '| '
    else:
        br = '<br>'
        start = ''

    try:
        module = importlib.import_module(args.module)
    except ImportError as e:
        raise SystemExit('Could not import %s: %s' % (args.module, e))
    doc = yaml.safe_load(module.DOCUMENTATION)
    x = prettytable.PrettyTable(
        ['Parameter', 'Choices/Defaults', 'Configuration', 'Comments']
    )
    for k in x.align:
        x.align[k] = 'l'

    options = doc.get('options', {})
    for name, data in sorted(options.items(), key=lambda t: t[0]):
        x.add_row([normalize(i, rst=args.rst) for i in (
            param(name, data, br=br, start=start),
            default(data),
            config(data, br=br, start=start),
            data['description']
        )])

    if args.rst:
        lines = x.get_string(hrules=prettytable.ALL).splitlines()
        lines[2] = lines[2].replace('-', '=')
        print('\n'.join(lines))
    else:
        print('\n'.join(x.get_string(junction_char='|').splitlines()[1:-1])) 
Example #16
Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def table(self):
        x = pt.PrettyTable(align = 'r', float_format = '1.3', hrules = pt.ALL)
        x.add_column("objval", self._objvals.tolist())
        x.add_column("solution", list(map(self.solution_string, self._solutions)))
        return str(x) 
Example #17
Source File: ui.py    From piston-cli with MIT License 5 votes vote down vote up
def print_permissions(account):
    t = PrettyTable(["Permission", "Threshold", "Key/Account"], hrules=allBorders)
    t.align = "r"
    for permission in ["owner", "active", "posting"]:
        auths = []
        for type_ in ["account_auths", "key_auths"]:
            for authority in account[permission][type_]:
                auths.append("%s (%d)" % (authority[0], authority[1]))
        t.add_row([
            permission,
            account[permission]["weight_threshold"],
            "\n".join(auths),
        ])
    print(t) 
Example #18
Source File: HXTool.py    From Hyperflex-Hypercheck with MIT License 5 votes vote down vote up
def create_sub_report(ip):
    # create HX controller report file
    global subreportfiles
    filename = "HX_Report_" + str(ip) +".txt"
    subreportfiles.append(filename)
    with open(filename, "w") as fh:
        fh.write("\t\t\t     HX Health Check " + str(toolversion))
        fh.write("\r\n")
        fh.write("\t\t\tHX Controller: " + ip)
        fh.write("\r\n")
        fh.write("\t\t\tHX Hostname: " + hostd[ip].get("hostname", ""))
        fh.write("\r\n")
        fh.write("#" * 80)
        fh.write("\r\n")
        n = 1
        for cname in testdetail[ip].keys():
            fh.write("\r\n" + str(n) + ") " + cname + ":")
            fh.write("\r\n")
            tw = PrettyTable(hrules=ALL)
            tw.field_names = ["Name", "Status", "Comments"]
            tw.align = "l"
            for k, v in testdetail[ip][cname].items():
                if type(v) == list:
                    tw.add_row([k, "\n".join(v), ""])
                elif type(v) == dict:
                    tw.add_row([k, v["Status"], v["Result"]])
                else:
                    tw.add_row([k, v, ""])
            fh.write((str(tw)).replace("\n", "\r\n"))
            fh.write("\r\n")
            n += 1

    #print("\r\nSub Report File: " + filename)
    log_msg(INFO, "Sub Report File: " + filename + "\r") 
Example #19
Source File: ui.py    From uptick with MIT License 5 votes vote down vote up
def format_table(table, hrules=False, align="l"):
    if not hrules:
        hrules = prettytable.FRAME
    else:
        hrules = prettytable.ALL

    header = [click.style(x, fg="red", bold=True) for x in table[0]]
    t = prettytable.PrettyTable(header, hrules=hrules)
    t.align = align
    for index, row in enumerate(table[1:]):
        row = [str(x) for x in row]
        row[0] = click.style(row[0], fg="yellow")
        t.add_row(row)
    return t 
Example #20
Source File: solution_classes.py    From risk-slim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def table(self):
        x = pt.PrettyTable(align = 'r', float_format = '1.4', hrules=pt.ALL)
        x.add_column("objval", self._objvals.tolist())
        x.add_column("solution", list(map(self.solution_string, self._solutions)))
        return str(x) 
Example #21
Source File: status.py    From kuryr-kubernetes with Apache License 2.0 4 votes vote down vote up
def _convert_annotations(self, test_fn, update_fn):
        updated_count = 0
        not_updated_count = 0
        malformed_count = 0
        pods = self.k8s.get('/api/v1/pods')['items']
        for pod in pods:
            try:
                obj = self._get_annotation(pod)
                if not obj:
                    # NOTE(dulek): We ignore pods without annotation, those
                    # probably are hostNetworking.
                    continue
            except Exception:
                malformed_count += 1
                continue

            if test_fn(obj):
                obj = update_fn(obj)
                serialized = obj.obj_to_primitive()
                try:
                    ann = {
                        constants.K8S_ANNOTATION_VIF:
                            jsonutils.dumps(serialized)
                    }
                    self.k8s.annotate(
                        pod['metadata']['selfLink'], ann,
                        pod['metadata']['resourceVersion'])
                except exceptions.K8sClientException:
                    print('Error when updating annotation for pod %s/%s' %
                          (pod['metadata']['namespace'],
                           pod['metadata']['name']))
                    not_updated_count += 1

                updated_count += 1

        t = prettytable.PrettyTable(['Stat', 'Number'],
                                    hrules=prettytable.ALL)
        t.align = 'l'

        cells = [['Updated annotations', updated_count],
                 ['Malformed annotations', malformed_count],
                 ['Annotations left', not_updated_count]]
        for cell in cells:
            t.add_row(cell)
        print(t)