Python prettytable.PrettyTable() Examples

The following are 30 code examples of prettytable.PrettyTable(). 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: interactive.py    From justcopy-backend with MIT License 6 votes vote down vote up
def process(question, candidates=None, top_n=1, n_docs=5):
    predictions = DrQA.process(
        question, candidates, top_n, n_docs, return_context=True
    )
    table = prettytable.PrettyTable(
        ['Rank', 'Answer', 'Doc', 'Answer Score', 'Doc Score']
    )
    for i, p in enumerate(predictions, 1):
        table.add_row([i, p['span'], p['doc_id'],
                       '%.5g' % p['span_score'],
                       '%.5g' % p['doc_score']])
    print('Top Predictions:')
    print(table)
    print('\nContexts:')
    for p in predictions:
        text = p['context']['text']
        start = p['context']['start']
        end = p['context']['end']
        output = (text[:start] +
                  colored(text[start: end], 'green', attrs=['bold']) +
                  text[end:])
        print('[ Doc = %s ]' % p['doc_id'])
        print(output + '\n') 
Example #2
Source File: Kmeans_AnFany.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy, method='AnFany'):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [method] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix

#  最终的程序 
Example #3
Source File: utils.py    From baiduyun with Apache License 2.0 6 votes vote down vote up
def show_table(request_flag, file_list_tmp):
    rows = ["序列号", "文件/目录名", "文件大小"]
    if WIN_PLATFORM:
        encoding = 'gbk'
    else:
        encoding = 'utf-8'
    table = PrettyTable(rows, encoding=encoding)
    if not request_flag:
        print(file_list_tmp)
        return
    global file_list
    file_list = file_list_tmp
    table.padding_width = 1
    for i, val in enumerate(file_list):
        table.add_row([i, val['name'], get_size_in_nice_string(val['size'])])
    print(table) 
Example #4
Source File: table_config.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def show_data(cls):
        """display stored data in table"""
        if not len(cls.select()):
            click.echo(highlight_text("No entry found !!!"))
            return

        table = PrettyTable()
        table.field_names = ["NAME", "UUID", "LAST UPDATED"]
        for entity in cls.select():
            entity_data = entity.get_detail_dict()
            last_update_time = arrow.get(
                entity_data["last_update_time"].astimezone(datetime.timezone.utc)
            ).humanize()
            table.add_row(
                [
                    highlight_text(entity_data["name"]),
                    highlight_text(entity_data["uuid"]),
                    highlight_text(last_update_time),
                ]
            )
        click.echo(table) 
Example #5
Source File: table_config.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def show_data(cls):
        """display stored data in table"""

        if not len(cls.select()):
            click.echo(highlight_text("No entry found !!!"))
            return

        table = PrettyTable()
        table.field_names = ["NAME", "UUID", "LAST UPDATED"]
        for entity in cls.select():
            entity_data = entity.get_detail_dict()
            last_update_time = arrow.get(
                entity_data["last_update_time"].astimezone(datetime.timezone.utc)
            ).humanize()
            table.add_row(
                [
                    highlight_text(entity_data["name"]),
                    highlight_text(entity_data["uuid"]),
                    highlight_text(last_update_time),
                ]
            )
        click.echo(table) 
Example #6
Source File: roundRobinWithScoreboard.py    From paper.io.sessdsa with GNU General Public License v3.0 6 votes vote down vote up
def cur_status():
    firstRowOfTable = [' ']
    for i in range(len(players)):
        firstRowOfTable += [players[i][0]]
    x = PrettyTable(firstRowOfTable + ['Score'])

    for i in range(len(players)):
        x.add_row([players[i][0]] + boardRaw[i] + [board[i][4]])
        x.add_row([' '] * (len(players) + 2))

    os.system('clear')
    print(x, file=sys.__stdout__)

    # 积分条
    out = sorted(board, key=itemgetter(-1, 1, 0), reverse=True)
    for i in range(len(out)):
        print(
            '%15s%3d %s' % (out[i][0], out[i][-1], "----" * out[i][-1]),
            file=sys.__stdout__) 
Example #7
Source File: query.py    From google-analytics with ISC License 6 votes vote down vote up
def serialize(self, format=None, with_metadata=False):
        names = [column.name for column in self.columns]

        if not format:
            return self.as_dict(with_metadata=with_metadata)
        elif format == 'json':
            return json.dumps(self.as_dict(with_metadata=with_metadata), indent=4)
        elif format == 'csv':
            buf = utils.StringIO()
            writer = csv.writer(buf)
            writer.writerow(names)
            writer.writerows(self.rows)
            return buf.getvalue()
        elif format == 'ascii':
            table = prettytable.PrettyTable(names)
            table.align = 'l'
            for row in self.rows:
                table.add_row(row)
            if with_metadata:
                return utils.format("""
                    {title}
                    {table}
                    """, title=self.queries[0].title, table=table)
            else:
                return table 
Example #8
Source File: app.py    From conjure-up with MIT License 6 votes vote down vote up
def show_env():
    """ Shows environment variables from post deploy actions
    """
    print("Available environment variables: \n")
    table = PrettyTable()
    table.field_names = ["ENV", "DEFAULT", ""]
    table.align = 'l'
    for step in app.steps:
        for x in step.additional_input:
            default = colored(x.get('default', ''), 'green', attrs=['bold'])
            key = colored(x['key'], 'blue', attrs=['bold'])
            table.add_row([key, default,
                           textwrap.fill(step.description, width=55)])
    print(table)
    print("")

    url = ("https://docs.ubuntu.com/conjure-up/"
           "en/usage#customising-headless-mode")
    print(
        textwrap.fill(
            "See {} for more information on using these variables to further "
            "customize your deployment.".format(url), width=79))
    sys.exit(0) 
Example #9
Source File: ProxyManage.py    From Pansidong with GNU General Public License v3.0 6 votes vote down vote up
def get_alive_proxy(self, amount=0, delay=0):
        """
        从数据库中获取获取存活的代理
        :param amount: 取出的数量
        :param delay: 取出延时小于delay的代理
        """
        all_ips = self.session.query(Proxy)
        all_ips = all_ips.filter(Proxy.is_alive == "1")
        if int(delay):
            all_ips = all_ips.filter(Proxy.times < delay)
        all_ips = all_ips.order_by(Proxy.times)
        if int(amount):
            all_ips = all_ips.limit(amount)

        result = all_ips.all()
        # TODO:在Windows上要设置GBK编码,mac未测试。
        # Linux 上需要设置为UTF-8编码
        encoding = "UTF-8" if "linux" in platform.system().lower() else "GBK"
        x = prettytable.PrettyTable(encoding=encoding, field_names=["Proxy IP", "Location", "Proxy Type", "Delay (s)"],
                                    float_format=".2")
        for res in result:
            x.add_row([res.ip + ":" + res.port, res.location, res.proxy_type, float(res.times)])
        x.align = "l"
        print x
        print "[*] Total: {}".format(str(len(result))) 
Example #10
Source File: Kmeans_Sklearn.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy, method='Sklearn'):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [method] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix

# 将sklearn输出的结果变为字典形式 
Example #11
Source File: LR_TensorFlow.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [' '] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix

# 构建函数 
Example #12
Source File: LR_AnFany.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [' '] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix

# 返回混淆矩阵用到的数据TP,TN,FP,FN 
Example #13
Source File: Softmax_AnFany.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy, method='AnFany'):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [method] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix

# 主函数 
Example #14
Source File: Softmax_Sklearn.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy, method='Sklearn'):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [method] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix


# 将独热编码的类别变为标识为1,2,3的类别 
Example #15
Source File: CatBoost_Classify_adult.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def ConfuseMatrix(reallist, prelist, dcix=data.exdixxt):
    '''
    :param reallist: 真实的类别列表
    :param prelist: 预测的类别列表
    :return: 输出混淆矩阵
    '''

    # 首先将字典的键值互换
    ruid = {}
    for jj in dcix:
        ruid[dcix[jj]] = jj

    zidian = Tom(reallist, prelist)
    lieming = sorted(zidian.keys())
    table = PT(['混淆矩阵'] + ['预测%s' % ruid[d] for d in lieming])
    for jj in lieming:
        table.add_row(['实际%s' % ruid[jj]] + [zidian[jj][kk] for kk in lieming])
    return table

#  计算F1度量的函数 
Example #16
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 #17
Source File: basics.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def shards(self, ctx):
        """Get a list of shards"""
        table = PrettyTable()
        table.field_names = ["Shard-Id", "Latency", "Guilds", "Users"]
        shards = await self.bot.get_shards()
        for shard in sorted(shards, key=lambda s: s["id"]):
            latency = f"{round(shard['latency'] * 1000, 1)} ms"
            if (datetime.utcnow() - shard["seen"]) > timedelta(minutes=3):
                latency = "offline?"

            table.add_row([str(shard["id"]), latency, helpers.format_number(shard["guilds"]),
                           helpers.format_number(shard["users"])])

        pages = formatter.paginate(str(table))
        for page in pages:
            await ctx.send(f"```diff\n{page}```") 
Example #18
Source File: admin.py    From xenon with GNU General Public License v3.0 6 votes vote down vote up
def query(self, ctx, timeout: float = 0.5, *, expression: str):
        """
        Evaluate a single expression on all shards and return the results


        __Arguments__

        **expressions**: The expression
        """
        results = await self.bot.query(expression, timeout=timeout)
        table = PrettyTable()
        table.field_names = ["Shard-Id", "Result"]
        for shards, result in sorted(results, key=lambda r: sum(r[0])):
            table.add_row([", ".join([str(s) for s in shards]), result])

        pages = formatter.paginate(str(table))
        for page in pages:
            await ctx.send(f"```diff\n{page}```") 
Example #19
Source File: movies.py    From iquery with MIT License 6 votes vote down vote up
def pretty_print(self):

        pt = PrettyTable()
        pt._set_field_names(self.header)
        for m in self.movies:
            pt.add_row(m)
        print(pt)

        print('输入编号获取剧情简介:')
        while True:
            raw = input('>> ')
            if raw in ('q', 'quit'):
                exit()
            try:
                num = int(raw)
            except ValueError:
                print('Invalid number.')
                continue

            if (num - 1) in range(len(self)):
                self._get_movie_summary(num)
            else:
                print('Invalid number.') 
Example #20
Source File: hospitals.py    From iquery with MIT License 6 votes vote down vote up
def pretty_print(self):

        if not self._hospital:
            pt = PrettyTable()
            pt._set_field_names([self._city])
            for hospital in self.putian_hospitals_in_city:
                pt.add_row([colored.green(hospital)])
            print(pt)

        else:
            is_putian, field_name = False, self._city + self._hospital

            for hospital in self.putian_hospitals_in_city:
                pt = PrettyTable()
                if self._hospital in hospital:
                    is_putian, field_name = True, hospital
                    pt._set_field_names([field_name])
                    pt.add_row([colored.green(str(is_putian))])
                    print(pt) 
Example #21
Source File: Softmax_TensorFlow.py    From Machine-Learning-for-Beginner-by-Python3 with MIT License 6 votes vote down vote up
def confusion(realy, outy, method='TensorFlow'):
    mix = PrettyTable()
    type = sorted(list(set(realy.T[0])), reverse=True)
    mix.field_names = [method] + ['预测:%d类'%si for si in type]
    # 字典形式存储混淆矩阵数据
    cmdict = {}
    for jkj in type:
        cmdict[jkj] = []
        for hh in type:
            hu = len(['0' for jj in range(len(realy)) if realy[jj][0] == jkj and outy[jj][0] == hh])
            cmdict[jkj].append(hu)
    # 输出表格
    for fu in type:
        mix.add_row(['真实:%d类'%fu] + cmdict[fu])
    return mix
# 将独热编码的类别变为标识为1,2,3的类别 
Example #22
Source File: lottery.py    From iquery with MIT License 6 votes vote down vote up
def pretty_print(self):
        pt = PrettyTable()
        pt._set_field_names(self.header)
        # align left
        pt.align["开奖号码"] = "l"
        pt.align["奖池滚存(元)"] = "l"
        for item in self.lotteries:
            pt.add_row(item)
        print(pt)

        print('输入编号获取相应彩种往期中奖号码:')
        while True:
            raw = input('>> ')
            if raw in ('q', 'quit'):
                exit()
            try:
                num = int(raw)
            except ValueError:
                print('Invalid number.请按编号栏输入编号')
                continue

            if (num - 1) in range(len(self._rows)):
                self.get_lottery_detail(num)
            else:
                print('Invalid number.') 
Example #23
Source File: layout.py    From netutils-linux with MIT License 6 votes vote down vote up
def make_table(header, align_map=None, rows=None):
    """ Wrapper for pretty table """
    table = PrettyTable()
    table.horizontal_char = table.vertical_char = table.junction_char = ' '
    try:
        table.field_names = header
    except Exception as err:
        print_(header)
        raise err
    if align_map:
        for field, align in zip(header, align_map):
            table.align[field] = align
    if rows:
        for row in rows:
            if len(row) < len(table.field_names):
                continue
            try:
                table.add_row(row)
            except Exception as err:
                print_('fields:', table.field_names)
                print_('row:', row)
                print_('rows:', rows)
                raise err
    return table 
Example #24
Source File: commands.py    From drydock with Apache License 2.0 6 votes vote down vote up
def node_list(ctx, output='table'):
    """List nodes."""
    nodelist = NodeList(ctx.obj['CLIENT']).invoke()

    if output == 'table':
        pt = PrettyTable()

        pt.field_names = [
            'Node Name', 'Status', 'CPUs', 'Memory', 'PXE MAC', 'Mgmt IP',
            'IPMI IP', 'Power State'
        ]

        for n in nodelist:
            pt.add_row([
                n['hostname'], n['status_name'], n['cpu_count'], n['memory'],
                n['boot_mac'], n['boot_ip'], n['power_address'],
                n['power_state']
            ])

        click.echo(pt)
    elif output == 'json':
        click.echo(json.dumps(nodelist)) 
Example #25
Source File: engine.py    From justcopy-backend with MIT License 6 votes vote down vote up
def process(self, question, candidates=None, top_n=1, n_docs=5):
        predictions = self.DrQA.process(
            question, candidates, top_n, n_docs, return_context=True
        )
        table = prettytable.PrettyTable(
            ['Rank', 'Answer', 'Doc', 'Answer Score', 'Doc Score']
        )
        for i, p in enumerate(predictions, 1):
            table.add_row([i, p['span'], p['doc_id'],
                        '%.5g' % p['span_score'],
                        '%.5g' % p['doc_score']])
        print('Top Predictions:')
        print(table)
        print('\nContexts:')
        for p in predictions:
            text = p['context']['text']
            start = p['context']['start']
            end = p['context']['end']
            output = (text[:start] +
                    colored(text[start: end], 'green', attrs=['bold']) +
                    text[end:])
            print('[ Doc = %s ]' % p['doc_id'])
            print(output + '\n')
        return predictions 
Example #26
Source File: print_utils.py    From g3ar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_rows(heads, rows, color=''):
    """Print Column With Color.
    
    Params:
        heads: :list: the row of heads
        rows: :list tuple: the rows data(list or tuple)
        coler: :str: 
            lightblack_ex
            magenta
            cyan
            green
            blue
            yellow
            red
    
    Returns:
        return the strings of table 
    """
    assert len(heads) == len(rows[0])
    assert isinstance(color, str)
    
    _prefix = ''
    if hasattr(Fore, color.upper()):
        _prefix = getattr(Fore, color.upper())
    
    #
    # split rows
    #
    table = PrettyTable(heads)
    for row in rows:
        table.add_row(row)
    
    
    raw = table.get_string()
    init(autoreset=True)
    print(_prefix + raw)
    return table 
Example #27
Source File: word_similarity.py    From Word_Similarity_and_Word_Analogy with Apache License 2.0 5 votes vote down vote up
def pprint(self, result):
        from prettytable import PrettyTable
        x = PrettyTable(["Dataset", "Found", "Not Found", "Score (rho)"])
        x.align["Dataset"] = "l"
        for k, v in result.items():
            x.add_row([k, v[0], v[1], v[2]])
        print(x) 
Example #28
Source File: tui.py    From conjure-up with MIT License 5 votes vote down vote up
def show_summary(self):
        utils.info("Post-Deployment Step Results")
        table = PrettyTable()
        table.field_names = ["Application", "Result"]
        for step in app.steps:
            table.add_row(self._format_step_result(step))
        print(table) 
Example #29
Source File: pretty_flake8.py    From designate with Apache License 2.0 5 votes vote down vote up
def main():

    raw_errors = []

    max_filename_len = 0
    for line in sys.stdin:
        m = re.match(PEP8_LINE, line)
        if m:
            m = m.groupdict()
            raw_errors.append(m)
            if len(m['file']) > max_filename_len:
                max_filename_len = len(m['file'])
        else:
            print(line)

    if len(raw_errors) > 0:

        print('Flake8 Results')

        ct = PrettyTable([
            "File",
            "Line",
            "Column",
            "Error Code",
            "Error Message",
            "Code"
        ])

        ct.align["File"] = "l"
        ct.align["Error Message"] = "l"
        ct.align["Code"] = "l"

        for line in raw_errors:
            ct.add_row(format_dict(line))

        print(ct)

        with open('flake8_results.html', 'w') as f:
            f.write('<html><head><style type="text/css">table a:link{color:#666;font-weight:700;text-decoration:none}table a:visited{color:#999;font-weight:700;text-decoration:none}table a:active,table a:hover{color:#bd5a35;text-decoration:underline}table{font-family:Arial,Helvetica,sans-serif;color:#666;font-size:12px;text-shadow:1px 1px 0 #fff;background:#eaebec;margin:20px;border:1px solid #ccc;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;-moz-box-shadow:0 1px 2px #d1d1d1;-webkit-box-shadow:0 1px 2px #d1d1d1;box-shadow:0 1px 2px #d1d1d1}table th{padding:21px 25px 22px;border-top:1px solid #fafafa;border-bottom:1px solid #e0e0e0;background:#ededed;background:-webkit-gradient(linear,left top,left bottom,from(#ededed),to(#ebebeb));background:-moz-linear-gradient(top,#ededed,#ebebeb)}table th:first-child{text-align:left;padding-left:20px}table tr:first-child th:first-child{-moz-border-radius-topleft:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px}table tr:first-child th:last-child{-moz-border-radius-topright:3px;-webkit-border-top-right-radius:3px;border-top-right-radius:3px}table tr{text-align:left;padding-left:20px}table td:first-child{text-align:left;padding-left:20px;border-left:0}table td{padding:18px;border-top:1px solid #fff;border-bottom:1px solid #e0e0e0;border-left:1px solid #e0e0e0;background:#fafafa;background:-webkit-gradient(linear,left top,left bottom,from(#fbfbfb),to(#fafafa));background:-moz-linear-gradient(top,#fbfbfb,#fafafa)}table tr.even td{background:#f6f6f6;background:-webkit-gradient(linear,left top,left bottom,from(#f8f8f8),to(#f6f6f6));background:-moz-linear-gradient(top,#f8f8f8,#f6f6f6)}table tr:last-child td{border-bottom:0}table tr:last-child td:first-child{-moz-border-radius-bottomleft:3px;-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px}table tr:last-child td:last-child{-moz-border-radius-bottomright:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px}table tr:hover td{background:#f2f2f2;background:-webkit-gradient(linear,left top,left bottom,from(#f2f2f2),to(#f0f0f0));background:-moz-linear-gradient(top,#f2f2f2,#f0f0f0)}</style></head><body>%s</body</html>' % ct.get_html_string(attributes = {"cellspacing": 0})) # noqa 
Example #30
Source File: print_utils.py    From g3ar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def print_column(head, column, color=''):
    """Print Column With Color.
    
    Params:
        head: :: A head for the column data.
        column: :list tuple: the column data(list or tuple)
        coler: :str: 
            lightblack_ex
            magenta
            cyan
            green
            blue
            yellow
            red
    
    Returns:
        return the strings of table 
    """
    assert isinstance(color, str)
    
    _prefix = ''
    if hasattr(Fore, color.upper()):
        _prefix = getattr(Fore, color.upper())
    
    table = PrettyTable()
    table.add_column(head, column)
    
    raw = table.get_string()
    init(autoreset=True)
    print(_prefix + raw)
    return table

#----------------------------------------------------------------------