本文整理汇总了Python中texttable.Texttable.add_rows方法的典型用法代码示例。如果您正苦于以下问题:Python Texttable.add_rows方法的具体用法?Python Texttable.add_rows怎么用?Python Texttable.add_rows使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类texttable.Texttable
的用法示例。
在下文中一共展示了Texttable.add_rows方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: print_steps
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def print_steps(self, show_result=True):
def max_len_of_list_of_str(s):
return max(len(line) for line in str(s).split('\n'))
def autodetect_width(d):
widths = [0] * len(d[0])
for line in d:
for _i in range(len(line)):
widths[_i] = max(widths[_i], max_len_of_list_of_str(line[_i]))
return widths
if self.save_history:
if self.errors:
self.history = self.history[:-1]
t = Texttable()
header = ['№', 'Term', 'Code'] if self.parallel else ['№', 'Term', 'Code', 'Stack']
data = [header] + [
[repr(i) for i in item][:-1] if self.parallel else [repr(i) for i in item] for item in self.history]
t.add_rows(data)
t.set_cols_align(['l'] + ['r'] * (len(header) - 1))
t.set_cols_valign(['m'] + ['m'] * (len(header) - 1))
t.set_cols_width(autodetect_width(data))
print t.draw()
else:
if not self.errors:
print ' Steps: %10s' % self.iteration
if show_result:
print 'Result: %10s' % repr(self.term)
示例2: dashboard_format
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def dashboard_format(self, records):
"""Format modeled records in dashboard format.
Args:
records: Modeled records to format.
Returns:
str: Record data in dashboard format.
"""
title = util.hline(self.title_fmt % {'model_name': records[0].name.capitalize(),
'storage_path': records[0].storage}, 'cyan')
header_row = [col['header'] for col in self.dashboard_columns]
rows = [header_row]
for record in records:
populated = record.populate()
row = []
for col in self.dashboard_columns:
if 'value' in col:
try:
cell = populated[col['value']]
except KeyError:
cell = 'N/A'
elif 'yesno' in col:
cell = 'Yes' if populated.get(col['yesno'], False) else 'No'
elif 'function' in col:
cell = col['function'](populated)
else:
raise InternalError("Invalid column definition: %s" % col)
row.append(cell)
rows.append(row)
table = Texttable(logger.LINE_WIDTH)
table.set_cols_align([col.get('align', 'c') for col in self.dashboard_columns])
table.add_rows(rows)
return [title, table.draw(), '']
示例3: test_colored
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def test_colored():
table = Texttable()
table.set_cols_align(["l", "r", "c"])
table.set_cols_valign(["t", "m", "b"])
table.add_rows([
[get_color_string(bcolors.GREEN, "Name Of Person"), "Age", "Nickname"],
["Mr\nXavier\nHuon", 32, "Xav'"],
[get_color_string(bcolors.BLUE,"Mr\nBaptiste\nClement"),
1,
get_color_string(bcolors.RED,"Baby")] ])
expected_output = dedent("""
+----------------+-----+----------+
| [92mName Of Person[0m | Age | Nickname |
+================+=====+==========+
| Mr | | |
| Xavier | 32 | |
| Huon | | Xav' |
+----------------+-----+----------+
| [94mMr[0m | | |
| [94mBaptiste[0m | 1 | |
| [94mClement[0m | | [91mBaby[0m |
+----------------+-----+----------+
""").strip('\n')
assert table.draw() == expected_output
示例4: print_diff_as_table
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def print_diff_as_table(self, include=None, exclude=None,
deco_border=False, deco_header=False,
deco_hlines=False, deco_vlines=False):
diffdict = self.diff(include, exclude)
if not diffdict:
return
from texttable import Texttable
table = Texttable()
deco = 0
if deco_border:
deco |= Texttable.BORDER
if deco_header:
deco |= Texttable.HEADER
if deco_hlines:
deco |= Texttable.HLINES
if deco_vlines:
deco |= Texttable.VLINES
table.set_deco(deco)
sortedkey = sorted(diffdict)
table.add_rows(
[[''] + self._name] +
[[keystr] + [self._getrepr(diffdict[keystr], name)
for name in self._name]
for keystr in sortedkey]
)
print table.draw()
示例5: per_class_metrics
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def per_class_metrics(self, labels, predictions):
_, counts = np.unique(labels, return_counts=True)
precision, recall, _, _ = score(labels, predictions)
C = confusion_matrix(labels, predictions)
avg_acc_per_class = np.average(recall)
t = Texttable()
t.add_rows([
['Metric', 'CAR', 'BUS', 'TRUCK', 'OTHER'],
['Count labels'] + counts.tolist(),
['Precision'] + precision.tolist(),
['Recall'] + recall.tolist()
])
t2 = Texttable()
t2.add_rows([
['-', 'CAR', 'BUS', 'TRUCK', 'OTHER'],
['CAR'] + C[0].tolist(),
['BUS'] + C[1].tolist(),
['TRUCK'] + C[2].tolist(),
['OTHER'] + C[3].tolist()
])
return t, t2, avg_acc_per_class
示例6: containers_to_ascii_table
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def containers_to_ascii_table(containers):
"""Just a method that formats the images to ascii table.
Expects dictionary {host: [images]}
and prints multiple tables
"""
with closing(StringIO()) as out:
for host, values in containers.iteritems():
out.write("[" + str(host) + "] \n")
t = TextTable(max_width=400)
t.set_deco(TextTable.HEADER)
t.set_cols_dtype(['t'] * 6)
t.set_cols_align(["l"] * 6)
t.set_cols_width([12, 25, 25, 15, 20, 15])
rows = []
rows.append(
['Id', 'Image', 'Command', 'Created', 'Status', 'Ports'])
for container in values:
rows.append([
container.id[:12],
container.image,
container.command[:20],
time_ago(container.created),
container.status,
container.ports
])
t.add_rows(rows)
out.write(t.draw() + "\n\n")
return out.getvalue()
示例7: main
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def main(args):
"""
process each argument
"""
table = Texttable()
table.set_cols_align(["r", "r", "r", "r", "r"])
rows = [["Number", "File Name", "File Size", "Video Duration (H:MM:SS)", "Conversion Time"]]
total_time = 0.0
total_file_size = 0
for index, arg in enumerate(args, start=1):
timer = utils.Timer()
with timer:
result = resize(arg, (index, len(args)))
#
result.elapsed_time = timer.elapsed_time()
rows.append([index,
result.file_name,
utils.sizeof_fmt(result.file_size),
utils.sec_to_hh_mm_ss(utils.get_video_length(result.file_name)) if result.file_name else "--",
"{0:.1f} sec.".format(result.elapsed_time) if result.status else FAILED])
#
if rows[-1][-1] != FAILED:
total_time += result.elapsed_time
total_file_size += result.file_size
table.add_rows(rows)
print table.draw()
print 'Total file size:', utils.sizeof_fmt(total_file_size)
print 'Total time: {0} (H:MM:SS)'.format(utils.sec_to_hh_mm_ss(total_time))
print utils.get_unix_date()
示例8: displayText
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def displayText(self):
column = 0
nbRow = 1
t = Texttable()
t.set_cols_align(["l", "c", "c", "c"])
title = ["/", "Tic", "Tac", "Toe"]
endLine = ["\\", 1, 2, 3]
adding = []
adding.append(nbRow)
for i in self.plateau.flat: # reads row by row
if i == 0:
adding.append("X")
elif i == 1:
adding.append("O")
else:
adding.append("")
column += 1
if column == self.lineCount:
t.add_rows([title, adding])
column = 0
nbRow += 1
adding = []
adding.append(nbRow)
t.add_rows([title, endLine])
print t.draw()
示例9: format_info
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def format_info(value, format, cols_width=None, dumper=None):
if format in(INFO_FORMAT.DICT, INFO_FORMAT.JSON, INFO_FORMAT.YAML):
value['component_details'] = json_loads(value['component_details'])
if format == INFO_FORMAT.JSON:
return json_dumps(value)
elif format == INFO_FORMAT.YAML:
buff = StringIO()
yaml.dump_all([value], default_flow_style=False, indent=4, Dumper=dumper, stream=buff)
value = buff.getvalue()
buff.close()
return value
elif format == INFO_FORMAT.TEXT:
cols_width = (elem.strip() for elem in cols_width.split(','))
cols_width = [int(elem) for elem in cols_width]
table = Texttable()
table.set_cols_width(cols_width)
# Use text ('t') instead of auto so that boolean values don't get converted into ints
table.set_cols_dtype(['t', 't'])
rows = [['Key', 'Value']]
rows.extend(sorted(value.items()))
table.add_rows(rows)
return table.draw()
else:
return value
示例10: output_table_list
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def output_table_list(tables):
terminal_size = get_terminal_size()[1]
widths = []
for tab in tables:
for i in range(0, len(tab.columns)):
current_width = len(tab.columns[i].label)
if len(widths) < i + 1:
widths.insert(i, current_width)
elif widths[i] < current_width:
widths[i] = current_width
for row in tab.data:
current_width = len(resolve_cell(row, tab.columns[i].accessor))
if current_width > widths[i]:
widths[i] = current_width
if sum(widths) != terminal_size:
widths[-1] = terminal_size - sum(widths[:-1]) - len(widths) * 3
for tab in tables:
table = Texttable(max_width=terminal_size)
table.set_cols_width(widths)
table.set_deco(0)
table.header([i.label for i in tab.columns])
table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
six.print_(table.draw() + "\n")
示例11: _create_website
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def _create_website(args):
api = _login(args)
if len(args.site_apps) % 2:
print('Error: invalid site applications array')
print('Array items should be pairs of application name and URL path')
print('Example: django_app / django_app_media /media')
return
else:
site_apps = zip(args.site_apps[::2], args.site_apps[1::2])
for site_app in site_apps:
app_name, app_url = site_app
if not VALID_SYMBOLS.match(app_name):
print('Error: %s is not a valid app name' % app_name)
print('use A-Z a-z 0-9 or uderscore symbols only')
return
if not VALID_URL_PATHS.match(app_url):
print('Error: %s is not a valid URL path' % app_url)
print('must start with / and only regular characters, . and -')
return
response = api.create_website(args.website_name, args.ip, args.https, \
args.subdomains, *site_apps)
print('Web site has been created:')
table = Texttable(max_width=140)
table.add_rows([['Param', 'Value']] + [[key, value] for key, value in response.items()])
print(table.draw())
示例12: display_two_columns
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def display_two_columns(cls, table_dict=None):
if table_dict:
ignore_fields = ['_cls', '_id', 'date_modified', 'date_created', 'password', 'confirm']
table = Texttable(max_width=100)
rows = [['Property', 'Value']]
for key, value in table_dict.iteritems():
if key not in ignore_fields:
items = [key.replace('_', ' ').title()]
if isinstance(value, list):
if value:
if key == "projects":
project_entry = ""
for itm in value:
user_project = Project.objects(id=ObjectId(itm.get('$oid'))) \
.only('title', 'project_id').first()
project_entry = project_entry + user_project.title + ", "
project_entry.strip(', ')
items.append(project_entry)
else:
items.append(' , '.join(value))
else:
items.append('None')
else:
items.append(value)
rows.append(items)
try:
if rows:
table.add_rows(rows)
except:
print sys.exc_info()[0]
print table.draw()
pass
示例13: draw
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def draw(self):
t = Texttable()
t.add_rows([["TEAM","RUNS","HITS","LOB","ERRORS"],
[self.away_team.team_name, self.away_runs, self.away_hits, self.away_LOB, self.away_errors],
[self.home_team.team_name, self.home_runs, self.home_hits, self.home_LOB, self.home_errors]])
print(t.draw())
示例14: output_table
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def output_table(tab):
max_width = get_terminal_size()[1]
table = Texttable(max_width=max_width)
table.set_deco(0)
table.header([i.label for i in tab.columns])
widths = []
number_columns = len(tab.columns)
remaining_space = max_width
# set maximum column width based on the amount of terminal space minus the 3 pixel borders
max_col_width = (remaining_space - number_columns * 3) / number_columns
for i in range(0, number_columns):
current_width = len(tab.columns[i].label)
tab_cols_acc = tab.columns[i].accessor
max_row_width = max(
[len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ]
)
current_width = max_row_width if max_row_width > current_width else current_width
if current_width < max_col_width:
widths.insert(i, current_width)
# reclaim space not used
remaining_columns = number_columns - i - 1
remaining_space = remaining_space - current_width - 3
if remaining_columns != 0:
max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns
else:
widths.insert(i, max_col_width)
remaining_space = remaining_space - max_col_width - 3
table.set_cols_width(widths)
table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
print(table.draw())
示例15: _create_app
# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import add_rows [as 别名]
def _create_app(args):
api = _login(args)
response = api.create_app(args.name, args.type, args.autostart, args.extra_info)
print('App has been created:')
table = Texttable(max_width=140)
table.add_rows([['Param', 'Value']] + [[key, value] for key, value in response.items()])
print(table.draw())