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