我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用prettytable.PrettyTable()。
def run_all(self): """Run all available testcases""" tiers_to_run = [] msg = prettytable.PrettyTable( header_style='upper', padding_width=5, field_names=['tiers', 'order', 'CI Loop', 'description', 'testcases']) for tier in self._tiers.get_tiers(): if (tier.get_tests() and re.search(CONST.__getattribute__('CI_LOOP'), tier.get_ci_loop()) is not None): tiers_to_run.append(tier) msg.add_row([tier.get_name(), tier.get_order(), tier.get_ci_loop(), textwrap.fill(tier.description, width=40), textwrap.fill(' '.join([str(x.get_name( )) for x in tier.get_tests()]), width=40)]) LOGGER.info("TESTS TO BE EXECUTED:\n\n%s\n", msg) for tier in tiers_to_run: self.run_tier(tier)
def lol_to_table(lol, format=None, headers=None): """ Args: lol (list): list of lists format (str): text headers (list): list of fields to be used as headers Return: obj - prettytable object """ table = PrettyTable(field_names=headers) for ds_row in lol: table.add_row([f for f in ds_row]) if format == 'text': table.set_style(PLAIN_COLUMNS) if format == 'word': table.set_style(MSWORD_FRIENDLY) table = table.get_string() return table
def process_init(problem_id, **session_options): if not problem_id.isdigit(): session = ProblemSession(config.polygon_url, None, **session_options) problems = session.send_api_request('problems.list', {}, problem_data=False) list = [] for i in problems: if i["name"] == problem_id: list.append(i) if len(list) == 0: print('No problem %s found' % problem_id) exit(0) if len(list) == 1: problem_id = list[0]["id"] print('Detected problem id is %s' % problem_id) if len(list) == 2: print('Problem %s is ambigious, choose by id' % problem_id) table = PrettyTable(['Id', 'Name', 'Owner', 'Access']) for i in list: table.add_row([i["id"], i["name"], i["owner"], i["accessType"]]) print(table) exit(0) global_vars.problem = ProblemSession(config.polygon_url, problem_id) save_session()
def display_s3_bucket_validations_table(self, bucketlist): ''' List the S3 buckets and the validation results in tabular format ''' # Setup Table. header = ["Bucket Name", "Profile", "Naming Policy", "Tag Validation", "Result"] table = prettytable.PrettyTable(header) for bucket in bucketlist: name = bucket['Name'] profile = bucket['profile_name'][0] naming_policy = bucket['validations']['nameresult'] tag_policy = textwrap.fill(bucket['validations']['tagresult'], 40) result = bucket['validations']['result'] row = [name, profile, naming_policy, tag_policy, result] table.add_row(row) print table
def __str__(self): try: assert self.project_name assert self.case_name result = 'PASS' if(self.is_successful( ) == TestCase.EX_OK) else 'FAIL' msg = prettytable.PrettyTable( header_style='upper', padding_width=5, field_names=['test case', 'project', 'duration', 'result']) msg.add_row([self.case_name, self.project_name, self.get_duration(), result]) return msg.get_string() except AssertionError: self.__logger.error("We cannot print invalid objects") return super(TestCase, self).__str__()
def show(self): env_info = super(CliEnv, self).show() msg = prettytable.PrettyTable( header_style='upper', padding_width=5, field_names=['Functest Environment', 'value']) for key, value in six.iteritems(env_info): if key is not None: msg.add_row([key, value]) click.echo(msg.get_string())
def sentimentanalysis(self, text_): """ Does sentiment analysis using SQLAlchemy API """ alchemyapi = AlchemyAPI() # import ipdb; ipdb.set_trace() if "" in text_.keys() and len(text_) < 2: print "No tweets to analyse were found!!" else: response = alchemyapi.sentiment("text", text_) sentrep = response["docSentiment"]["type"] lst = [sentrep] prettytable = PrettyTable(['Sentiment Type']) t = prettytable.add_row(lst) print prettytable
def get_pretty_table(possible_ivs): t = PrettyTable(["Level", "Atk IV", "Def IV", "Stam IV", "Perfection %"]) rows = [] for possible_iv in possible_ivs: rows.append([ possible_iv[IvStats.STAT_LEVEL], possible_iv[IvStats.STAT_ATK_IV], possible_iv[IvStats.STAT_DEF_IV], possible_iv[IvStats.STAT_STAM_IV], possible_iv[IvStats.PERFECTION_PERCENTAGE] ]) # Sort by completion %. rows = sorted(rows, key=lambda x: x[4]) for row in rows: t.add_row(row) return t
def show_cleaning_list(message): """???????????? :param message: slackbot.dispatcher.Message """ s = Session() dow2users = OrderedDict() cleaning = s.query(Cleaning).order_by(Cleaning.day_of_week.asc(), Cleaning.id.asc()) for c in cleaning: user = get_user_name(c.slack_id) dow2users.setdefault(c.day_of_week, []).append(user) pt = PrettyTable(['??', '????']) pt.align['????'] = 'l' for day_of_week, users in dow2users.items(): dow = DAY_OF_WEEK[day_of_week] str_users = ', '.join(users) pt.add_row([dow, str_users]) message.send('```{}```'.format(pt))
def show_user_alias_name(message, user_name=None): """?????????????????? :param message: slackbot?????????????class :param str user: Slack?????? """ if user_name: slack_id = get_slack_id_by_name(user_name) else: slack_id = message.body['user'] user_name = get_user_name(slack_id) if not slack_id: message.send('{}????Slack?user_id???????'.format(user_name)) return s = Session() alias_names = [user.alias_name for user in s.query(UserAliasName) .filter(UserAliasName.slack_id == slack_id)] pt = PrettyTable(['?????', 'Slack ID', '??????']) alias_name = ','.join(alias_names) pt.add_row([user_name, slack_id, alias_name]) message.send('```{}```'.format(pt))
def format_nested_dict(d, fields, column_names): if d is None: return '' pt = prettytable.PrettyTable(caching=False, print_empty=False, header=True, field_names=column_names) for n in column_names: pt.align[n] = 'l' keys = sorted(d.keys()) for field in keys: value = d[field] if not isinstance(value, six.string_types): value = jsonutils.dumps(value, indent=2, ensure_ascii=False) pt.add_row([field, value.strip('"')]) return pt.get_string()
def display_sql(cursor,title,header,padd): col_names = [cn[0].upper() for cn in cursor.description] rows = cursor.fetchall() sqlr = prettytable.PrettyTable() sqlr.header = header sqlr.padding_width = padd sqlr.hrules = prettytable.ALL sqlr.vrules = prettytable.ALL sqlr.title = title row_id = -1 for name in col_names: row_id += 1 sqlr.add_column(name, [row[row_id] for row in rows]) return sqlr # MCE Version Header
def main(): parser = argparse.ArgumentParser() parser.add_argument('-a', '--arch') parser.add_argument('-d', '--distro') parser.add_argument('-T', '--table', action='store_true') parser.add_argument('-v', '--verbose', action='count', default=0) parser.add_argument('repo', nargs='+') args = parser.parse_args() verbosity(args.verbose) repo = get_component(args) if isinstance(repo, FlatRepository): packages = repo.fetch_packages() else: packages = repo.fetch_packages(args.arch or dpkg_architecture()) if args.table: tbl = PrettyTable(tblcols) tbl.align = 'l' for pkg in packages: pkg['Description'] = pkg['Description'].splitlines()[0] tbl.add_row([pkg[c] for c in tblcols]) print(tbl.get_string()) else: for pkg in packages: print(json.dumps(pkg, default=for_json))
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))
def __str__(self): if len(self.data["templates"]) == 0: return "There are no templates set" table = prettytable.PrettyTable(["Index", "Path"]) list_to_highlight = [] for keys in self.data["templates"]: if int(keys) == self.template: list_to_highlight.append(keys) table.add_row([keys] +[self.data["templates"][keys]]) table_string = table.get_string() table_list = table_string.split("\n") for keys in list_to_highlight: table_list[int(keys) + 2] = color.BOLD + table_list[int(keys) + 2] + color.END return "\n".join(table_list)
def __str__(self): if len(self.data["accounts"]) == 0: return "There are no accounts set" table = prettytable.PrettyTable(["Index", "Website", "Username"]) list_to_highlight = [] for keys in self.data["accounts"]: if int(keys) == self.account: list_to_highlight.append(keys) table.add_row([keys] + self.data["accounts"][keys]) table_string = table.get_string() table_list = table_string.split("\n") for keys in list_to_highlight: table_list[int(keys) + 2] = color.BOLD + table_list[int(keys) + 2] + color.END return "\n".join(table_list)
def show_human_readable_pod_list(self): if self.result: items = self.result.get("results")[0].get("data").get("items") table = PrettyTable(["NAME", "READY", "STATUS", "RESTARTS", "AGE", "IP"]) table.align = "l" items = sorted(items, key=lambda x: parser.parse(x.get("metadata")["creationTimestamp"])) for i in items: restarts = i.get("status").get("containerStatuses") restarts_sum = 0 if restarts: for r in restarts: restarts_sum += r.get("restartCount") else: restarts_sum = None ip = i.get("status").get("podIP") status = i.get("status").get("phase") name = i.get("metadata").get("name") ready = "-/-" time = get_datetime_diff(i.get("metadata").get("creationTimestamp")) if not self.kwargs.get("deploy") or self.kwargs.get("deploy") in i.get("metadata").get("labels").values(): table.add_row([name, ready, status, restarts_sum, time, ip]) print(table) else: print(EMPTY_NAMESPACE)
def show_human_readable_service_list(self): if self.result: items = self.result.get("results")[0].get("data").get("items") table = PrettyTable(["NAME", "CLUSTER-IP", "EXTERNAL", "HOST", "PORT(S)", "AGE"]) table.align = "l" items = sorted(items, key=lambda x: parser.parse(x.get("metadata")["creationTimestamp"])) for i in items: name = i.get("metadata").get("name") is_external = i.get("metadata").get("labels").get("external") cluster_ip = i.get("spec").get("clusterIP") if i.get("spec").get("domainHosts") and is_external == "true": external_host = " ,\n".join(i.get("spec").get("domainHosts")) else: external_host = "--" ports = i.get("spec").get("ports") for p in range(len(ports)): if ports[p].get("port") == ports[p].get("targetPort"): ports[p] = ("%s/%s" % (ports[p].get("port"), ports[p].get("protocol"))) else: ports[p] = ("%s:%s/%s" % (ports[p].get("port"), ports[p].get("targetPort"), ports[p].get("protocol"))) sum_ports = " ,\n".join(ports) time = get_datetime_diff(i.get("metadata").get("creationTimestamp")) if not self.kwargs.get("deploy") or self.kwargs.get("deploy") in i.get("metadata").get("labels").values(): table.add_row([name, cluster_ip, is_external, external_host, sum_ports, time]) print(table)
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
def printoptions(modadd): try: print(" ") t = PrettyTable([colors.red +'Option', 'Value', 'Description'+colors.end]) t.add_row(["------","------","-----------"]) t.align = 'l' t.valing = 'm' t.border = False for key, val in modadd.variables.items(): t.add_row([key, val[0], val[1]]) print (t,'\n') try: print(modadd.option_notes,'\n') except(AttributeError): pass except Exception as error: print(colors.red+"error: module is corrupted\n") traceback.print_exc(file=sys.stdout) print(colors.end)
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')
def service_describe(arg_vars, project_root): path = project_root + "/ansible/roles" services = next(walk(path))[1] t = PrettyTable(['Service Name', 'Dependencies']) t.align = "l" for s in services: f = project_root + "/ansible/roles/" + s + "/defaults/main.yml" if exists(f): with open(f, "r") as stream: content = yaml.load(stream) or {} t.add_row([s, ", ".join(content.get('service_dependencies', []))]) else: t.add(row([s, ''])) print t
def machines_describe(arg_vars, project_root): cluster_id = arg_vars['cluster_id'] path = util.machine_profiles_path(project_root, cluster_id) if exists(path): files = [f for f in listdir(path) if isfile(join(path, f))] t = PrettyTable(['Profile ID', 'Size', 'Services', 'Desired Count']) t.align = "l" t.align["Desired Count"] = "c" for f in files: with open(path + "/" + f, 'r') as stream: content = yaml.load(stream) t.add_row([content['profile_id'], content['ec2_instance_type'], ", ".join(content.get('machine_services', [])), content['n_machine_instances']]) print t else: print_fail("No machine profiles were found for this cluster.")
def machines_list(arg_vars, project_root, hint=True): if hint: print_ok("Hint: Displaying cached contents. Refresh status with: engraver machines cache") print("") path = project_root + "/.engraver/clusters/" + arg_vars['cluster_id'] + ".json" if exists(path): t = PrettyTable(['', 'ID', 'Profile', 'Public DNS Name', 'Private IP']) t.align = "l" contents = open(path, 'r').read() machines = sorted(json.loads(contents), key=lambda k: k.get('tags').get('ProfileId')) for index, m in enumerate(machines): t.add_row([index + 1, m.get('id'), m.get('tags').get('ProfileId'), m.get('public_dns_name'), m.get('private_ip_address')]) print t else: print_fail("No cached contents found.")
def print_permissions(account): t = PrettyTable(["Permission", "Threshold", "Key/Account"], hrules=allBorders) t.align = "r" for permission in ["owner", "active"]: auths = [] # account auths: for authority in account[permission]["account_auths"]: auths.append("%s (%d)" % (Account(authority[0])["name"], authority[1])) # key auths: for authority in account[permission]["key_auths"]: auths.append("%s (%d)" % (authority[0], authority[1])) t.add_row([ permission, account[permission]["weight_threshold"], "\n".join(auths), ]) print(t)
def pprint_user_answer(id, count=MAX_COUNT): """???????? :param str id: ??ID :param int count: ???????????? """ user = User(id) row = PrettyTable( ["ID", "Support num", "Commit num", "Question", "Answer"]) row.align["Support num"] = "l" row.align["Commit num"] = "l" row.align["Question"] = "l" row.align["Answer"] = "l" answers = user.get_answers(count) row.padding_width = 1 i = 0 for answer in answers: record = list(answer) record.insert(0, i) row.add_row(record) i += 1 print(row)
def pprint_user_article(id, count=MAX_COUNT): """?????????? :param str id: ??ID :param int count: ???????????? """ user = User(id) row = PrettyTable(["ID", "Title", "Summary"]) row.align["Title"] = "l" row.align["Summary"] = "l" articles = user.get_articles(count) row.padding_width = 1 i = 0 for article in articles: record = list(article) record.insert(0, i) row.add_row(record) i += 1 print(row)
def pprint_user_ask(id, count=MAX_COUNT): """???????? :param str id: ??ID :param int count: ???????????? """ user = User(id) row = PrettyTable(["ID", "Vote num", "Ask num", "Followers", "Question"]) row.align["Vote num"] = "l" row.align["Ask num"] = "l" row.align["Followers"] = "l" row.align["Question"] = "l" asks = user.get_asks(count) row.padding_width = 1 i = 0 for ask in asks: record = list(ask) record.insert(0, i) row.add_row(record) i += 1 print(row)
def build_report(counts): overall, by_type = metrics(counts) x = PrettyTable() x.field_names = ["Category", "P", "R", "F1"] x.add_row(["OVERALL", "{:02.2f}".format((100. * overall.prec)), "{:02.2f}".format((100. * overall.rec)), "{:02.2f}".format((100. * overall.fscore))]) for i, m in sorted(by_type.items()): x.add_row([i, "{:02.2f}".format((100. * m.prec)), "{:02.2f}".format((100. * m.rec)), "{:02.2f}".format((100. * m.fscore))]) x.align["Category"] = "r" return x
def get_score_table(self): """ Return iteration performance on 'dev' part formatted as an ASCII table (prettytable object) :return: prettytable object """ x = PrettyTable() best_ite = self.get_best_iteration() x.field_names = ["Iteration", "Dev Score"] for i, (iter_nb, payload) in enumerate(sorted(self.iterations_log.items()), start=1): if best_ite == i: current_iter_nb = "**{:03d}**".format(iter_nb) else: current_iter_nb = "{:03d}".format(iter_nb) current_score = "{:.5f}".format(payload["dev_score"]) x.add_row([current_iter_nb, current_score]) return x
def show(self): utils.print_help('"Target info') i = 0 x = PrettyTable() x.field_names = ['index', 'host', 'port'] for target in self.__targets: x.add_row([i, target.host, target.port]) i += 1 utils.print_info(x) utils.print_help('Threads: ', end='') utils.print_info(str(self.__threads)) utils.print_help('Timeout: ', end='') utils.print_info(str(self.__timeout)) utils.print_help('Output: ', end='') utils.print_info(self.__output) # utils.print_info("Target info: {}\n" # "Threads: {}\n" # "Timeout: {}\n" # "Output: {}" # .format(self.__targets, self.__threads, self.__timeout, self.__output))
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)
def print_goods(search_result): """use validate search result to print a table :param search_result: search result in taobao and jd :return: None """ search_result = sort_by_money(search_result) goods_table = PrettyTable(TABLE_TITLE) for index, goods in enumerate(search_result): goods["index"] = index goods_row = [goods.get(item, None) for item in ITEM_KEY] goods_table.add_row(goods_row) print(colorful_text('ready to hands chopping?', Fore.CYAN)) print(goods_table) open_detail_page(search_result)
def process_init_contest(contest_id, **session_options): contest = ProblemSession(config.polygon_url, None, **session_options) problems = contest.get_contest_problems(contest_id) print(problems) result = PrettyTable(['Problem name', 'Problem id', 'Status']) for problem in problems.keys(): if os.path.exists(problem): result.add_row([problem, problems[problem], colors.error('Directory exists')]) else: try: os.mkdir(problem) old_path = os.getcwd() os.chdir(problem) process_init(str(problems[problem])) os.chdir(old_path) result.add_row([problem, problems[problem], colors.success('Done')]) except Exception as e: print(e) result.add_row([problem, problems[problem], colors.error('Exception during init')]) print(result)
def process_list(): files = global_vars.problem.get_all_files_list() local_files = global_vars.problem.local_files table = PrettyTable(['File type', 'Polygon name', 'Local path', 'Local name']) printed_local = set() for file in files: local = global_vars.problem.get_local_by_polygon(file) path = local.get_path() if local else 'None' name = local.name if local else 'None' table.add_row([file.type, file.name, path, name]) if name: printed_local.add(name) for file in local_files: if file.name in printed_local: continue table.add_row([file.type, '!' + file.polygon_filename, file.get_path(), file.name]) print(table)
def printTable(data): """ print a pretty table """ from prettytable import PrettyTable column_header_list = data[0].keys() x = PrettyTable() x.field_names = column_header_list for col in column_header_list: x.align[col] = "l" x.align[column_header_list[0]] = "r" x.padding_width = 1 for row in data: row_to_add = [] for col in column_header_list: row_to_add.append(row[col]) x.add_row(row_to_add) print x.get_string()
def status(): """ Fetch service status :return: """ if master_pid("c") is True: print colored(" SERVICE IS RUNNING... ", "white", "on_blue") h = PrettyTable([u"??ID", u"????"]) h.align[u"??ID"] = "l" h.align[u"????"] = "l" h.padding_width = 1 pid_list = processors_list("r") for pid in pid_list: try: if psutil.Process(pid).is_running(): h.add_row([pid, colored("RUNNING...",attrs=["bold"])]) else: h.add_row([colored(pid, "magenta", "on_yellow", attrs=["bold"]), colored("STOPED", "magenta", "on_yellow", attrs=["bold"])]) except psutil.NoSuchProcess: h.add_row([colored(pid, "yellow", attrs=["bold", "blink"]), colored("LOSTED", "red", attrs=["bold", "blink"])]) print h else: cmsg("SERVICE IS STOPED!", "e")
def print_update_list(lst, fields, formatters=None): """Print the stack-update --dry-run output as a table. This function is necessary to print the stack-update --dry-run output, which contains additional information about the update. """ formatters = formatters or {} pt = prettytable.PrettyTable(fields, caching=False, print_empty=False) pt.align = 'l' for change in lst: row = [] for field in fields: if field in formatters: row.append(formatters[field](change.get(field, None))) else: row.append(change.get(field, None)) pt.add_row(row) if six.PY3: print(encodeutils.safe_encode(pt.get_string()).decode()) else: print(encodeutils.safe_encode(pt.get_string()))
def clear_matrix(): try: for x in range (0, 8, 1): for y in range(0, 8, 1): mat.set_pixel(x, y, 1).update() for x in range (0, 8, 1): for y in range(0, 8, 1): mat.set_pixel(x, y, 0).update() except AttributeError: if mat == 0: print("Test mode: lighting pixels") for x in range (0, 8, 1): for y in range(0, 8, 1): testmatrix[x][y] = 0 matrix_printing = prettytable.PrettyTable() for row in testmatrix: matrix_printing.add_row(row) print(matrix_printing.get_string(header=False, border=False)) else: print("No module connected. Try again!")
def matrix(x,y,state): if state == True: state_numerical = 1 elif state == False: state_numerical = 0 try: mat.set_pixel(x, y, state_numerical).update() except AttributeError: if mat == 0: print("Test mode: lighting pixels") testmatrix[x][y] = state_numerical matrix_printing = prettytable.PrettyTable() for row in testmatrix: matrix_printing.add_row(row) print(matrix_printing.get_string(header=False, border=False)) else: print("No module connected. Try again!")
def display_status(status_data): for session in status_data: # Display heading and initiate table print "SESSION: " + session[0] table = PrettyTable(["MASTER", "STATUS", "CRAWL STATUS", "SLAVE NODE", "LAST SYNCED", "CHKPT TIME", "CHKPT COMPLETED", "CHKPT COMPLETION TIME"]) for row in session[2]: table.add_row([row["master_node"] + ":" + row["master_brick"], row["status"], row["crawl_status"], row["slave_node"], row["last_synced"], row["checkpoint_time"], row["checkpoint_completed"], row["checkpoint_completion_time"]]) # If Table has data if session[2]: print table else: # When no filters match print "-" print ("Active: {active} | Passive: {passive} | " "Faulty: {faulty} | Created: {created} | " "Offline: {offline} | Stopped: {stopped} | " "Initializing: {initializing} | " "Total: {total}".format(**session[1])) # Empty line in output print
def display_ec2_tags_table(self, tagsobj): ''' Display List of tags in tabular format ''' header = ["Resource Id", "Resource Type", "Profile", "Tags"] table = prettytable.PrettyTable(header) table.align['Tags'] = "l" for resid in tagsobj.keys(): resource_id = resid obj = tagsobj[resid] keys = obj.keys() resource_type = obj['ResourceType'] profile_name = obj['profile_name'] tags_str = "" for key in keys: if key.startswith('tag_'): tagname = key.split("tag_")[1] tags_str = tags_str + tagname + ": " + obj[key] + "\n" row = [resource_id, resource_type, profile_name, tags_str] table.add_row(row) row = ["-"*20, "-"*20, "-"*20, "-"*50] table.add_row(row) print table
def display_ec2_nw_interfaces_table(self, nw_interfaces): ''' Display Nw interfaces in tabular format. ''' header = ["Interface Id", "Description", "Status", "Attachment-Status", "Attachment-ID", "Account", "Zone"] table = prettytable.PrettyTable(header) table.align["Description"] = "l" for nw_interface in nw_interfaces: intf_id = nw_interface['NetworkInterfaceId'] intf_description = nw_interface['Description'] intf_status = nw_interface['Status'] intf_account = nw_interface['profile_name'] intf_zone = nw_interface['region'] if nw_interface.get('Attachment', None) is None: intf_attach_status = "NA" intf_attach_id = "NA" else: intf_attach_status = nw_interface['Attachment']['Status'] intf_attach_id = nw_interface['Attachment']['InstanceOwnerId'] if intf_attach_id == nw_interface['OwnerId']: intf_attach_id = nw_interface['Attachment']['InstanceId'] row = [intf_id, intf_description, intf_status, intf_attach_status, intf_attach_id, intf_account, intf_zone] table.add_row(row) print table
def display_iam_user_permissions_table(self, user_name, profile_perms): ''' Display tabular format ''' table = prettytable.PrettyTable() table.add_column("User Name", [user_name]) for profile in profile_perms.keys(): if profile_perms[profile] is None: continue statementstr = "" for statement in profile_perms[profile]: resources = statement['Resource'] actions = statement.get('Action', None) if not actions: actions = statement.get('NotAction', None) effect = statement['Effect'] #statementstr = statementstr + "-" * 29 + "\n" tempstr = "Resources: " + str(resources) statementstr = statementstr + self.fillstr(tempstr, 30) tempstr = "Actions: " + \ str(actions) statementstr = statementstr + self.fillstr(tempstr, 30) tempstr = "Effect: " + \ str(effect) statementstr = statementstr + self.fillstr(tempstr, 30) statementstr = statementstr + "-" * 29 + "\n" statementstr = textwrap.fill(statementstr, 34) table.add_column(profile, [statementstr], align="l") print table
def display_s3_summary_table(self, bucket_summary): ''' Display S3 Summary in Tabular output. ''' # Setup table header. header = ["Profile", "Total Bucket Count"] table = prettytable.PrettyTable(header) for profile in bucket_summary.keys(): row = [profile, bucket_summary[profile]['total_count']] table.add_row(row) print table # Setup table header (loc constraint) header = ["Location", "Bucket Count"] table = prettytable.PrettyTable(header) for profile in bucket_summary.keys(): row = ["-"*40, "-"*20] table.add_row(row) row = [profile, " "] table.add_row(row) row = ["-"*40, "-"*20] table.add_row(row) locs = bucket_summary[profile]['locs'] for loc in locs.keys(): row = [loc, bucket_summary[profile]['locs'][loc]] table.add_row(row) row = [" ", " "] table.add_row(row) print table
def perform_profile_operations(self, namespace): ''' Handle the profile operations ''' awsconfig = aws_config.AwsConfig() profiles = awsconfig.get_profiles() profile_summary = {} for profile in profiles: profile_summary[profile] = {} profile_summary[profile]['access_key_id'] = \ awsconfig.get_aws_access_key_id(profile) profile_summary[profile]['secret_access_key'] = \ awsconfig.get_aws_secret_access_key(profile) if namespace.output == "json": pprinter = pprint.PrettyPrinter() pprinter.pprint(profile_summary) else: # Setup table. header = ["Profile Name", "Access Key ID", "Secret Access Key"] table = prettytable.PrettyTable(header) for profile in profile_summary.keys(): row = [profile, profile_summary[profile]['access_key_id'], profile_summary[profile]['secret_access_key']] table.add_row(row) print table
def view(self): x = PrettyTable() x.align = "r" x.add_column("variable_name", self.variable_names) x.add_column("vtype", self.get_field_as_list('vtype')) x.add_column("sign", self.get_field_as_list('sign')) x.add_column("lb", self.get_field_as_list('lb')) x.add_column("ub", self.get_field_as_list('ub')) x.add_column("C_0j", self.get_field_as_list('C_0j')) print x
def print_string(results_dict): """ creates an easy printable string from a results dict """ max_hlen = 42 hlen = 7 + len(' '.join(list(results_dict))) maxlen = (max_hlen-7) // len(results_dict) -2 table = prettytable.PrettyTable(header=True, vrules=prettytable.NONE) table.border = False table.padding_width = 1 cv = True if type(results_dict[list(results_dict.keys())[0]][0]) is list else False if cv: table.add_column('', ['VAcc', 'V-F1', 'TAcc', 'T-F1']) else: table.add_column('', ['CAcc', 'C-F1', 'RAcc', 'R-F1']) for exp in results_dict: res = results_dict[exp] scores = [] if cv: for fold in res: scores.append(fold[:4]) scores = np.mean(scores,0) else: scores = np.array([res[0],res[1],res[2],res[3]]) table.add_column(exp[0:maxlen] if hlen > max_hlen else exp,['{:.1f}%'.format(x*100) for x in scores]) return table.get_string()