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
python类PrettyTable()的实例源码
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 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()