python类AsciiTable()的实例源码

zabbix_api.py 文件源码 项目:zabbix_manager 作者: BillWang139967 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:do-latency 作者: dizballanze 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
scannt.py 文件源码 项目:new 作者: atlj 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:new 作者: atlj 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
draft.py 文件源码 项目:football_tools 作者: johnshiver 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
neural_network.py 文件源码 项目:ML-From-Scratch 作者: eriklindernoren 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
ms4.py 文件源码 项目:viper-metascan 作者: securenetworx 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:ovh-cli 作者: ovh 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:ovh-cli 作者: ovh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
output.py 文件源码 项目:ovh-cli 作者: ovh 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
terminaltables_adapter.py 文件源码 项目:cli_helpers 作者: dbcli 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
cm_network.py 文件源码 项目:CManager 作者: fachrioktavian 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
cm_interfaces.py 文件源码 项目:CManager 作者: fachrioktavian 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
search.py 文件源码 项目:spider163 作者: Chengyumeng 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
search.py 文件源码 项目:spider163 作者: Chengyumeng 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
search.py 文件源码 项目:spider163 作者: Chengyumeng 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
search.py 文件源码 项目:spider163 作者: Chengyumeng 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
resultview.py 文件源码 项目:dashbase-tools 作者: dashbase 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
resultview.py 文件源码 项目:dashbase-tools 作者: dashbase 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
resultview.py 文件源码 项目:dashbase-tools 作者: dashbase 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
check_tap.py 文件源码 项目:singer-tools 作者: singer-io 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
print_formats.py 文件源码 项目:infrared 作者: redhat-openstack 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:pyradio-nepal 作者: sandipbgt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
utils.py 文件源码 项目:pyradio-nepal 作者: sandipbgt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
repl.py 文件源码 项目:GrimREPL 作者: emehrkay 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
config.py 文件源码 项目:new 作者: atlj 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
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)
images.py 文件源码 项目:mocker 作者: tonybaloney 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def run(self, *args, **kwargs):
        images = self.list_images()
        table = AsciiTable(images)
        print(table.table)
basepolicy.py 文件源码 项目:orangengine 作者: lampwins 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
basepolicy.py 文件源码 项目:orangengine 作者: lampwins 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
basepolicy.py 文件源码 项目:orangengine 作者: lampwins 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号