Python terminaltables 模块,AsciiTable() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用terminaltables.AsciiTable()

项目:zabbix_manager    作者:BillWang139967    | 项目源码 | 文件源码
def __generate_output(self,output_list):
        '''
        ????
        ???????
        '''
        if self.output:
            if self.terminal_table:
                #table=AsciiTable(output_list)
                table=AsciiTable(output_list)
                print(table.table)
            else:
                for output in output_list:
                    for output_sub in output:
                        output_sub=output_sub.replace('\n', ',')
                        print("[%s]"%output_sub,end=" ")
                    print()
            print("sum: ",len(output_list[1:]))
项目:do-latency    作者:dizballanze    | 项目源码 | 文件源码
def start_test(ping_count=10, file_size="10mb", udp=False):
    results = {key: [] for key in REGIONS}
    # Latency testing
    pbar = tqdm(total=(len(REGIONS) * ping_count), desc=PADDING_FORMAT.format("Latency testing"), bar_format=BAR_FORMAT, leave=True)
    for region, host in six.iteritems(REGIONS):
        pbar.set_description(PADDING_FORMAT.format("Latency testing ({})".format(region)))
        results[region].append(do_ping(host, count=ping_count, udp=udp, hook=lambda: pbar.update(1)))
    pbar.close()
    # Download speed testing
    pbar = tqdm(total=(len(REGIONS) * 100), desc=PADDING_FORMAT.format("Download speed testing"), bar_format=BAR_FORMAT, leave=True, disable=False)
    for region, host in six.iteritems(REGIONS):
        pbar.set_description(PADDING_FORMAT.format("Download speed testing ({})".format(region)))
        url = "http://{}/{}.test".format(host, file_size)
        results[region].append(do_download(url, lambda progress: pbar.update(progress)))
    # Output sorted by latency results as table
    table_data = [[key] + value for key, value in six.iteritems(results)]
    table_data.sort(key=lambda row: float(row[1]))
    table_data.insert(0, ["Region", "Latency (ms)", "Download speed (mbps)"])
    table = AsciiTable(table_data)
    print("\n\n{}\n".format( table.table))
项目:new    作者:atlj    | 项目源码 | 文件源码
def scan():
    get_gateway()
    scan = os.popen("nmap " + gateway + "/24 -n -sP ").read()
    f = open(os.getcwd()+'/scanlog.txt','w')
    f.write(scan)
    f.close()
    devices = os.popen(" grep report "+os.getcwd()+"/scanlog.txt | awk '{print $5}'").read()
    devices_mac = os.popen("grep MAC "+os.getcwd()+"/scanlog.txt | awk '{print $3}'").read() + os.popen("ip addr | grep 'state UP' -A1 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'").read().upper()# get devices mac and localhost mac address
    devices_name = os.popen("grep MAC "+os.getcwd()+"/scanlog.txt | awk '{print $4 ,S$5 $6}'").read() + "\033[1;32m(Bu Cihaz)\033[0m"
    table_data = [
        ['IP Adres', 'Mac Adres','Uretici'],
        [devices, devices_mac,devices_name]
        ]
    table = AsciiTable(table_data)
    print("[+]------------------[Aginizda Bulunan Cihazlar ]----------------[+]\n")
    print(table.table)
项目:new    作者:atlj    | 项目源码 | 文件源码
def main():
    check_if_first_run()
    getform()
    if first_run:
     print("\n\n\tlutfen bir sonraki sayfada\n\tcinsiyetinizi belirtiniz\n\tdevam etmek icin bir tusa basin.")
     input("")
    getgender(first_run)
    saveload(first_run)
    definehitap()
    table_data = [['Kulanici adi','Assistan'],
                  [user.isim+' '+hitap,user.assistant]]
    table = AsciiTable(table_data)
    print(G+table.table+W)



    yazi1 = 'Hos geldiniz {} {}'
    print(user.assistant, ": ", yazi1.format(user.isim, hitap))
    shell.shellinit()
    shell.shell()

#ctrl c de hata vermemesi icin
项目:football_tools    作者:johnshiver    | 项目源码 | 文件源码
def print_top_available_players(self, position='QB', n=15):
        valid_positions = Player.POSITION_CHOICES
        # reduce tuples to single element
        valid_positions = map(lambda x: x[0], valid_positions)
        if position and position not in valid_positions:
            raise ValueError("{} must be one of {}".format(position,
                                                           valid_positions))

        table_data = [
            ['ID', 'Player', 'Position', 'Points'],
        ]

        players = self.available_players.all()
        if position:
            players = players.filter(position=position)
        top_players = sorted(players, key=lambda x: x.draft_bot_score,
                             reverse=True)
        for player in top_players[:n]:
            table_data.append([player.playerid, player.full_name, player.position,
                               int(player.draft_bot_score)])

        table = AsciiTable(table_data)
        print(table.table)
项目:ML-From-Scratch    作者:eriklindernoren    | 项目源码 | 文件源码
def summary(self, name="Model Summary"):
        # Print model name
        print (AsciiTable([[name]]).table)
        # Network input shape (first layer's input shape)
        print ("Input Shape: %s" % str(self.layers[0].input_shape))
        # Iterate through network and get each layer's configuration
        table_data = [["Layer Type", "Parameters", "Output Shape"]]
        tot_params = 0
        for layer in self.layers:
            layer_name = layer.layer_name()
            params = layer.parameters()
            out_shape = layer.output_shape()
            table_data.append([layer_name, str(params), str(out_shape)])
            tot_params += params
        # Print network configuration table
        print (AsciiTable(table_data).table)
        print ("Total Parameters: %d\n" % tot_params)
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_analyzed_info(self):
        summary_table = [["Filename", "md5", "status"]]
        for path, name in self.files:
            av_found_threat = 0
            details = [["Engine", "Threat", "Def. time"]]
            res = self.metascan.scan_file_and_get_results(path, name, self.workflow)
            jres = res.json()
            for engine, scan_details in jres["scan_results"]["scan_details"].iteritems():
                if scan_details.get("scan_result_i"):
                    av_found_threat += 1
                def_time = parser.parse(scan_details["def_time"]).strftime("%Y-%m-%d %H:%M:%S")
                details.append([engine, scan_details["threat_found"], def_time])
            status = "%d/%d" % (av_found_threat, jres["scan_results"]["total_avs"])
            summary_table.append([name, jres["file_info"]["md5"], status])
            table = AsciiTable(details, name)
            print table.table
        return summary_table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def display_full_users(users):
    """Display the list of users with all information."""
    data = [['Login', 'Home', 'State', 'Ssh', 'Primary account']]

    # Sort the list of users by login
    users = sorted(users, key=lambda k: k['login'])

    for user in users:
        data.append([
            user['login'],
            user['home'],
            user['state'],
            user['sshState'],
            user['isPrimaryAccount']
        ])

    table = AsciiTable(data)

    return table.table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def display_config(configs):
    """Display the .ovhconfig file information."""
    data = [['#ID', 'Environment', 'Engine version', 'Container', 'Path',
             'Engine', 'Firewall']]

    for config in configs:
        data.append([
            config['id'],
            config['environment'],
            config['engineVersion'],
            config['container'],
            config['path'],
            config['engineName'],
            config['httpFirewall']
        ])

    table = AsciiTable(data)

    return table.table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def iter_plain(self, data):
        """Iterate over a plain data."""

        def get_value(value):
            if not value and not isinstance(value, bool):
                return ''
            elif (isinstance(value, list)) and len(value) == 0:
                return ''
            elif isinstance(value, list):
                return value
            elif isinstance(value, dict):
                return json.dumps(value, sort_keys=True, ensure_ascii=False)

            return str(value)

        d = [[k, get_value(v)]
             for k, v in sorted(data.items())
             if k not in self.exclude]

        d.insert(0, ['Property', 'Value'])

        table = AsciiTable(d)

        return table.table
项目:cli_helpers    作者:dbcli    | 项目源码 | 文件源码
def adapter(data, headers, table_format=None, **kwargs):
    """Wrap terminaltables inside a function for TabularOutputFormatter."""
    keys = ('title', )

    table_format_handler = {
        'ascii': terminaltables.AsciiTable,
        'double': terminaltables.DoubleTable,
        'github': terminaltables.GithubFlavoredMarkdownTable,
    }

    table = table_format_handler[table_format]

    t = table([headers] + list(data), **filter_dict_by_key(kwargs, keys))

    dimensions = terminaltables.width_and_alignment.max_dimensions(
        t.table_data,
        t.padding_left,
        t.padding_right)[:3]
    for r in t.gen_table(*dimensions):
        yield u''.join(r)
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def get_scanning_result(self, iface):
        indent = ' ' * 1
        flagExec = self.exec_iwlist(iface)
        if flagExec:
            header = indent + 'Scanning WiFi networks using interface \'' + iface + '\'\n'
            network_table = [['SSID', 'AP Address', 'Channel', 'Encryption', 'Quality']]
            for dict_network in self.parsed_cells:
                network_table.append([
                    dict_network['Name'],
                    dict_network['Address'],
                    dict_network['Channel'],
                    dict_network['Encryption'],
                    dict_network['Quality']
                ])
            table = AsciiTable(network_table)
            print (Fore.YELLOW + Style.DIM + header + table.table)
            return True
        else:
            return False
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def print_ifaces_wireless_table(self):
        indent = ' ' * 1
        header = indent + 'Wireless interfaces information:\n'
        self.wireless_table = [['Interface', 'Status', 'IP Address',
                                'Mask', 'Mode', 'SSID', 'AP Address', 'Wireless Type']]
        for data in self.ifaces_wireless:
            self.wireless_table.append([
                data,
                self.dict_status[data],
                self.dict_ipaddr[data],
                self.dict_mask[data],
                self.dict_mode[data],
                self.dict_ssid[data],
                self.dict_apaddr[data],
                self.dict_wname[data]
            ])
        table = AsciiTable(self.wireless_table)
        print (Fore.YELLOW + Style.DIM + header + table.table)
项目:spider163    作者:Chengyumeng    | 项目源码 | 文件源码
def searchSong(key):
    url = uapi.search_api
    data = {'s': key, 'offset': 0, 'limit': 20, 'type': "1"}
    req = requests.post(url, headers=uapi.header, data=data, timeout=10)
    if req.json()["result"]['songCount'] == 0:
        pylog.log.warn("??? {} ???????".format(key))
        return
    songs = req.json()["result"]['songs']
    song_table = AsciiTable([["ID", "??", "??", "??"]])
    for item in songs:
        id = item['id']
        name = (item['name']).encode("utf-8")
        album = (item['album']['name']).encode("utf-8")
        artist = []
        for a in item['artists']:
            artist.append(a['name'].encode("utf-8"))
        song_table.table_data.append([str(id), name, album, ",".join(artist)])
    print(pylog.Blue("? \"{}\" ?????".format(key)))
    print(song_table.table)
项目:spider163    作者:Chengyumeng    | 项目源码 | 文件源码
def searchAlbum(key):
    url = uapi.search_api
    data = {'s': key, 'offset': 0, 'limit': 20, 'type': "10"}
    req = requests.post(url, headers=uapi.header, data=data, timeout=10)
    if req.json()["result"]['albumCount'] == 0:
        pylog.log.warn("??? {} ???????".format(key))
        return
    albums = req.json()["result"]['albums']
    song_table = AsciiTable([["ID", "??", "??","???"]])
    for item in albums:
        id = item['id']
        name = item['name'].encode("utf-8")
        company = ""
        if item['company'] !=  None:
            company = item['company'].encode("utf-8")
        artist = []
        for a in item['artists']:
            artist.append(a['name'].encode("utf-8"))
        song_table.table_data.append([str(id), name, ",".join(artist), company])
    print(pylog.Blue("? \"{}\" ?????".format(key)))
    print(song_table.table)
项目:spider163    作者:Chengyumeng    | 项目源码 | 文件源码
def searchSinger(key):
    url = uapi.search_api
    data = {'s': key, 'offset': 0, 'limit': 10, 'type': "100"}
    req = requests.post(url, headers=uapi.header, data=data, timeout=10)
    if req.json()["result"]['artistCount'] == 0:
        pylog.log.warn("??? {} ????????".format(key))
        return
    artists = req.json()["result"]['artists']
    song_table = AsciiTable([["ID", "??", "????", "MV??"]])
    for item in artists:
        id = str(item['id'])
        name = item['name'].encode("utf-8")
        acount = str(item['albumSize'])
        mcount = str(item['mvSize'])
        song_table.table_data.append([id, name, acount, mcount])
    print(pylog.Blue("? \"{}\" ?????".format(key)))
    print(song_table.table)
项目:spider163    作者:Chengyumeng    | 项目源码 | 文件源码
def searchPlaylist(key):
    url = uapi.search_api
    data = {'s': key, 'offset': 0, 'limit': 5, 'type': "1000"}
    req = requests.post(url, headers=uapi.header, data=data, timeout=10)
    if req.json()["result"]['playlistCount'] == 0:
        pylog.log.warn("??? {} ???????".format(key))
        return
    playlists = req.json()["result"]['playlists']
    song_table = AsciiTable([["ID", "??", "???", "????", "????"]])
    for item in playlists:
        id = str(item['id'])
        name = item['name'].encode("utf-8")
        creator = item['creator']['nickname'].encode("utf-8")
        pcount = str(item['playCount'])
        bcount = str(item['bookCount'])
        song_table.table_data.append([id, name, creator, pcount, bcount])
    print(pylog.Blue("? \"{}\" ?????".format(key)))
    print(song_table.table)
项目:dashbase-tools    作者:dashbase    | 项目源码 | 文件源码
def print_ts_aggregation(name, histograms):
    header_names = ["start", "end", "count"]
    data = [header_names]
    if histograms is not None:
        interval = histograms["bucketSizeInSeconds"]
        title = name + "(interval = {})".format(hms_string(interval))
        table = AsciiTable(data, title)
        buckets = histograms["histogramBuckets"]
        for bucket in buckets:
            start = format_time_value(bucket["timeInSec"])
            end = format_time_value(bucket["timeInSec"] + interval)
            count = "{:,}".format(bucket["count"])
            data_array = [start, end, count]
            data.append(data_array)
    else:
        table = AsciiTable(data, name)
    print(table.table)
项目:dashbase-tools    作者:dashbase    | 项目源码 | 文件源码
def print_tsa_aggregation(name, tsa, sub_req):
    header_names = ["start", "end", "bucket"]
    data = [header_names]
    if tsa is not None:
        interval = tsa["bucketSizeInSeconds"]
        title = name + "(interval = {})".format(hms_string(interval))
        table = AsciiTable(data, title)
        buckets = tsa["buckets"]
        for bucket in buckets:
            start = format_time_value(bucket["timeInSec"])
            end = format_time_value(bucket["timeInSec"] + interval)
            agg_str = draw_agg_resp(bucket["response"], sub_req)
            if agg_str is None:
                agg_str = "n/a"
            data_array = [start, end, agg_str]
            data.append(data_array)
    else:
        table = AsciiTable(data, name)
    print(table.table)
项目:dashbase-tools    作者:dashbase    | 项目源码 | 文件源码
def print_table_info(name, table_info):
    metrics_info = table_info["metrics"]

    metrics_data = [["type", "time unit", "volume"]]
    indexing_info = metrics_info["indexing"]
    metrics_data.append(["bytes", "per second", sizeof_fmt(indexing_info["numBytesPerSecond"])])
    metrics_data.append(["bytes", "per day", sizeof_fmt(indexing_info["numBytesPerDay"])])
    metrics_data.append(["events", "per second", "{:,}".format(indexing_info["numEventsPerSecond"])])
    metrics_data.append(["events", "per day", "{:,}".format(indexing_info["numEventsPerDay"])])

    metrics_table = AsciiTable(metrics_data, name + ": ingestion")
    print(metrics_table.table)

    cluster_info = table_info["info"]
    partitions_data = [["partition", "hosts"]]
    partitions_table = AsciiTable(partitions_data, name + ": partitions")
    for partition in cluster_info.keys():
        host_list = cluster_info[partition]
        partitions_data.append([partition, "\r".join(host_list)])
    print(partitions_table.table)
项目:singer-tools    作者:singer-io    | 项目源码 | 文件源码
def print_summary(summary):

    print('The output is valid.')
    print('It contained {} messages for {} streams.'.format(
        summary.num_messages(), len(summary.streams)))
    print('')
    print('{:7} schema messages'.format(summary.num_schemas()))
    print('{:7} record messages'.format(summary.num_records()))
    print('{:7} state messages'.format(summary.num_states))
    print('')
    print('Details by stream:')
    headers = [['stream', 'records', 'schemas']]
    rows = [[s.name, s.num_records, s.num_schemas]
            for s in summary.streams.values()]
    data = headers + rows

    table = AsciiTable(data)
    print(table.table)
项目:infrared    作者:redhat-openstack    | 项目源码 | 文件源码
def fancy_table(table_headers, *table_rows):
    """Creates a fancy table string from the given data

    :param table_headers: Iterable contains the table's headers
    :param table_rows: Iterable elements contain the table rows (body)
    :return: Formatted string represents the newly created table
    """
    # coloring class degrates gracefully if output is redirected so we will
    # not endup with ANSI escapes if we redirect console.
    table_data = [[c for c in table_headers]]
    table_data.extend(table_rows)

    table = AsciiTable(table_data=table_data)
    table.inner_row_border = True

    return table.table
项目:pyradio-nepal    作者:sandipbgt    | 项目源码 | 文件源码
def pretty_print_stations(stations=[], search=None):
    """
    prints all the radio stations in a table
    """
    from terminaltables import AsciiTable
    data = [['S.N.', 'NAME', 'LOCATION', 'FREQUENCY']]
    data.extend([[v['count'], v['name'], v['location'], v['frequency']] for v in stations
                        if search and search.lower() in v['name'].lower() or not search])
    print(AsciiTable(data).table)
项目:pyradio-nepal    作者:sandipbgt    | 项目源码 | 文件源码
def pretty_print(stations, search=None):
    from terminaltables import AsciiTable

    datas = [['S.N.', 'NAME', 'LOCATION', 'FREQUENCY'],]

    for counter, station in enumerate(stations):
        if search and search in station['name'] or not search:
            datas.append([counter + 1, station['name'], station['location'], station['frequency']])

    table = AsciiTable(datas)
    print(table.table)
项目:GrimREPL    作者:emehrkay    | 项目源码 | 文件源码
def table(self, headers, data):
        data = [headers] + data
        table = AsciiTable(data)
        table.inner_row_border = False
        self.tables.append(table.table)
        self.tables.append('\n\n')

        return self
项目:new    作者:atlj    | 项目源码 | 文件源码
def runl():
    column1 = 'Figlet\nAndroidpy'
    column2 = '     ' + figlet + '\n' + '     ' + androidpy
    column3 = '[0]\n[1]'
    tabledata = [
        ['Modul', 'Su Anki Ayari', 'Index'], [column1, column2, column3]]
    table = AsciiTable(tabledata)
    print(shell.textmain, "lutfen degistirmek istediginiz ayarin yanindaki Index degerini giriniz menu icin " + C + "\"ctrl + c\""+ W + " tuslarina basiniz.")
    print("\t", table.table)
项目:mocker    作者:tonybaloney    | 项目源码 | 文件源码
def run(self, *args, **kwargs):
        images = self.list_images()
        table = AsciiTable(images)
        print(table.table)
项目:orangengine    作者:lampwins    | 项目源码 | 文件源码
def to_table(self, with_names=False):
        """Return the policy as an ascii tables

        Args:
            with_names (bool): Include object names
        """
        table_header = self.table_header()

        table_row = self.table_row(with_names=with_names)

        table = AsciiTable([table_header, table_row])
        table.title = "Policy: " + self.name

        return table.table
项目:orangengine    作者:lampwins    | 项目源码 | 文件源码
def source_table(self, service_focus=True):

        table_header = ["Dst Zones", "Dst Addresses", "Services", "Action"]
        table_data = [table_header] + self._table_rows(self.source_lookup_object, True, service_focus)
        table = AsciiTable(table_data)
        table.title = "Effective Policy: " + self.target + " as source"

        return table.table
项目:orangengine    作者:lampwins    | 项目源码 | 文件源码
def destination_table(self, service_focus=True):

        table_header = ["Src Zones", "Src Addresses", "Services", "Action"]
        table_data = [table_header] + self._table_rows(self.destination_lookup_object, False, service_focus)
        table = AsciiTable(table_data)
        table.title = "Effective Policy: " + self.target + " as destination"

        return table.table
项目:zops    作者:bjinwright    | 项目源码 | 文件源码
def user_credentials(ctx,app_name,stage_name):
    result = Zops(app_name,stage_name,
                  profile_name=ctx.obj['profile_name']).user_stack_outputs()
    try:
        table_data = [
            [i['OutputKey'], i['OutputValue']]
            for i in result
            ]
    except TypeError:
        click.echo('User creds not ready yet.')
        return
    table_data.insert(0, ['Attribute','Value'])
    table = terminaltables.AsciiTable(table_data)
    click.echo(table.table)
项目:football_tools    作者:johnshiver    | 项目源码 | 文件源码
def show_top_players(cls, position="RB", n=15):
        """
        Displays top x players given position.
        """
        valid_positions = cls.POSITION_CHOICES
        # reduce tuples to single element
        valid_positions = map(lambda x: x[0], valid_positions)
        if position not in valid_positions:
            raise ValueError("{} must be one of {}".format(position,
                                                           valid_positions))

        table_data = [
            ['Player', 'Position', 'Points'],
        ]

        players = Player.objects.all()
        if position:
            players = players.filter(position=position)
        top_players = sorted(players, key=lambda x: x.draft_bot_score,
                             reverse=True)
        for player in top_players[:n]:
            table_data.append([player.full_name, player.position,
                               int(player.draft_bot_score)])

        table = AsciiTable(table_data)
        print(table.table)
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_analyzed_info(self):
        summary_table = [["Filename", "md5", "status"]]
        for path, name in self.files:
            av_found_threat = 0
            details = [["Engine", "Threat", "Def. time"]]
            res = self.metascan.scan_file_and_get_results(path, name)
            try:
                res.raise_for_status()
            except HTTPError as err:
                self.log('error', err)
                return
            jres = res.json()
            if jres.get("process_info", {}).get("result") == "Blocked":
                details = [["Blocked", "Reason: %s " % jres["process_info"]["blocked_reason"]]]
                status = "blocked"
            else:
                for engine, scan_details in jres["scan_results"]["scan_details"].iteritems():
                    if scan_details.get("scan_result_i"):
                        av_found_threat += 1
                    def_time = parser.parse(scan_details["def_time"]).strftime("%Y-%m-%d %H:%M:%S")
                    details.append([engine, scan_details["threat_found"], def_time])
                status = "%d/%d" % (av_found_threat, jres["scan_results"]["total_avs"])
            summary_table.append([name, jres["file_info"]["md5"], status])
            table = AsciiTable(details, name)
            print table.table
        return summary_table
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_summary(self, summary_table):
        sum_table = AsciiTable(summary_table, "Summary")
        print sum_table.table
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_engines(self):
        details = [["Engine name", "Engine version", "Def time", "Active"]]
        engines = self.metascan.get_engines()
        try:
            engines.raise_for_status()
        except HTTPError as err:
            self.log('error', err)
            return
        for eng in engines.json():
            def_time = parser.parse(eng["def_time"]).strftime("%Y-%m-%d %H:%M:%S")
            active = "Y" if eng["active"] else "N"
            details.append([eng["eng_name"], eng["eng_ver"], def_time, active])
        table = AsciiTable(details, "Engines")
        print table.table
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_summary(summary_table):
        sum_table = AsciiTable(summary_table, "Summary")
        print sum_table.table
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_workflows(self):
        details = []
        workflows = self.metascan.get_workflows()
        for wf in workflows.json():
            details.append([wf["name"]])
        table = AsciiTable(details, "Workflows")
        table.inner_heading_row_border = False
        print table.table
项目:viper-metascan    作者:securenetworx    | 项目源码 | 文件源码
def show_license(self):
        licenses = self.metascan.get_license()
        details = []
        for lic in licenses.json().iteritems():
            details.append([str(lic[0]), str(lic[1])])
        table = AsciiTable(details, "Licenses")
        table.inner_heading_row_border = False
        print table.table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def display_services(services):
    """Display the user services."""
    data = [['Services']]

    for service in sorted(services):
        data.append([service])

    table = AsciiTable(data)

    return table.table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def display_quota(quota):
    """Display the quota for a service."""
    used = '{} {}'.format(
        "%.2f" % quota['used']['value'],
        quota['used']['unit']
    )
    size = '{} {}'.format(
        "%.2f" % quota['size']['value'],
        quota['size']['unit']
    )

    table = AsciiTable([["Used", used], ["Size", size]])

    return table.table
项目:ovh-cli    作者:ovh    | 项目源码 | 文件源码
def display_users(users):
    """Display the list of users by their username."""
    data = [['Users']]

    for user in sorted(users):
        data.append([user])

    table = AsciiTable(data)

    return table.table
项目:sff    作者:nevarezs    | 项目源码 | 文件源码
def _print_table(self, data):
        """Print table to stdout."""
        max_width = 45
        wrapped_data = \
            [["\n".join(wrap(col, max_width))
                if ((type(col) is str or type(col) is unicode)
                    and len(col) > max_width)
                else col
                for col in row]
                for row in data]
        table = AsciiTable(wrapped_data)
        table.inner_row_border = True
        print table.table
项目:gce-manager    作者:binary-com    | 项目源码 | 文件源码
def get_ascii_table(self, table):
        return AsciiTable(table).table
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def show_profile(self):
        indent = ' '
        header = indent + 'List of profiles saved by system:\n'
        table = [['Profile name', 'Connection type', 'SSID', 'Passphrase']]
        list_profile = os.listdir(self.profile_path)
        for fileconf in list_profile:
            of_file = open(self.profile_path + fileconf, 'r')
            of = of_file.read().split('\n')
            if of[0][1::] == 'Open':
                table.append([fileconf[:-5:], 'Open', of[2][7:-1:], '-'])
            elif of[0][1::] == 'WPA':
                table.append([fileconf[:-5:], 'WPA', of[2][7:-1:], of[3][7:-1:]])
            of_file.close()
        print (Fore.YELLOW + Style.DIM + header + AsciiTable(table).table)
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def print_ifaces_ethernet_table(self):
        indent = ' ' * 1
        header = indent + 'Ethernet interfaces information:\n'
        self.ethernet_table = [['Interface', 'Status', 'IP Address', 'Mask']]
        for data in self.ifaces_ethernet:
            self.ethernet_table.append([
                data,
                self.dict_status[data],
                self.dict_ipaddr[data],
                self.dict_mask[data]
            ])
        table = AsciiTable(self.ethernet_table)
        print (Fore.YELLOW + Style.DIM + header + table.table)
项目:CManager    作者:fachrioktavian    | 项目源码 | 文件源码
def print_ifaces_localhost_table(self):
        indent = ' ' * 1
        header = indent + 'Localhost interfaces information:\n'
        self.localhost_table = [['Interface', 'Status', 'IP Address', 'Mask']]
        for data in self.ifaces_localhost:
            self.localhost_table.append([
                data,
                self.dict_status[data],
                self.dict_ipaddr[data],
                self.dict_mask[data]
            ])
        table = AsciiTable(self.localhost_table)
        print (Fore.YELLOW + Style.DIM + header + table.table)
项目:cointrader    作者:toirl    | 项目源码 | 文件源码
def colorize_value(value):
    if value < 0:
        return colored(value, "red")
    else:
        return colored(value, "green")


# def render_signal_details(signals):
#     out = [["Indicator", "Signal", "Details"]]
#     for s in signals:
#         out.append([s, signals[s].value, signals[s].details])
#     table = AsciiTable(out).table
#     return "\n".join(["\nSignal:", table])
项目:cointrader    作者:toirl    | 项目源码 | 文件源码
def render_bot_statistic(stat):
    out = [["", stat["start"], stat["end"], "CHANGE %"]]
    out.append(["COINTRADER", stat["trader_start_value"], stat["trader_end_value"], "{}".format(colorize_value(round(stat["profit_cointrader"], 4)))])
    out.append(["MARKET", stat["market_start_value"], stat["market_end_value"], "{}".format(colorize_value(round(stat["profit_chart"], 4)))])
    table = AsciiTable(out).table
    return "\n".join(["\nStatistic:", table])
项目:cointrader    作者:toirl    | 项目源码 | 文件源码
def render_bot_tradelog(trades):
    out = [["DATE", "TYPE", "RATE", "COINS", "COINS'", "BTC", "BTC'"]]
    for trade in trades:
        values = []
        values.append(trade.date)
        values.append(trade.order_type)
        values.append(trade.rate)
        if trade.order_type == "BUY":
            values.append("--")
            values.append(trade.amount_taxed)
            values.append(trade.btc)
            values.append("--")
        elif trade.order_type == "SELL":
            values.append(trade.amount)
            values.append("--")
            values.append("--")
            values.append(trade.btc_taxed)
        else:
            values.append(trade.amount)
            values.append("--")
            values.append(trade.btc)
            values.append("--")
        out.append(values)
    table = AsciiTable(out).table

    return "\n".join(["\nTradelog:", table])
项目:spider163    作者:Chengyumeng    | 项目源码 | 文件源码
def get_playlist(self, playlist_id):
        self.view_capture(int(playlist_id))
        url = uapi.playlist_api.format(playlist_id)
        s = requests.session()
        s = BeautifulSoup(s.get(url, headers=self.__headers).content, "html.parser")
        playlist = json.loads(s.text)['result']

        print("?" + playlist['name'].encode('utf-8') + "?")
        author = playlist['creator']['nickname'].encode('utf-8')
        pc = str(playlist['playCount'])
        sc = str(playlist['subscribedCount'])
        rc = str(playlist['shareCount'])
        cc = str(playlist['commentCount'])
        print("????{}  ???{} ???{} ???{} ???{}".format(author, pc, sc, rc, cc))
        print("???{}".format(playlist['description'].encode('utf-8')))
        print("???{}".format(",".join(playlist['tags']).encode("utf-8")))

        tb = [["ID", "????", "???", "??"]]
        for music in playlist['tracks']:
            artists = []
            for s in music['ar']:
                artists.append(s['name'])
            ms = music['name'].encode("utf-8")
            ar = ",".join(artists).encode("utf-8")
            ab = music['album']['name'].encode("utf-8")
            id = music['id']
            tb.append([id, ms, ar, ab])
        print(AsciiTable(tb).table)