本文整理汇总了Python中terminaltables.AsciiTable类的典型用法代码示例。如果您正苦于以下问题:Python AsciiTable类的具体用法?Python AsciiTable怎么用?Python AsciiTable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AsciiTable类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: print_table
def print_table(data):
"""Print the table of detected SSIDs and their data to screen.
Positional arguments:
data -- list of dictionaries.
"""
table = AsciiTable([COLUMNS])
table.justify_columns[2] = 'right'
table.justify_columns[3] = 'right'
table.justify_columns[4] = 'right'
table_data = list()
for row_in in data:
row_out = [
str(row_in.get('ssid', '')).replace('\0', ''),
str(row_in.get('security', '')),
str(row_in.get('channel', '')),
str(row_in.get('frequency', '')),
str(row_in.get('signal', '')),
str(row_in.get('bssid', '')),
]
if row_out[3]:
row_out[3] += ' MHz'
if row_out[4]:
row_out[4] += ' dBm'
table_data.append(row_out)
sort_by_column = [c.lower() for c in COLUMNS].index(OPTIONS['--key'].lower())
table_data.sort(key=lambda c: c[sort_by_column], reverse=OPTIONS['--reverse'])
table.table_data.extend(table_data)
print(table.table)
开发者ID:0x90,项目名称:libnl,代码行数:31,代码来源:scan_access_points.py
示例2: write_out_results
def write_out_results(self):
stats = self._calc_stats()
rps = stats.rps
results_table_data = [
['Item', 'Value', 'Info'],
['Successful calls', '%r'%stats.count, '测试成功的连接数'],
['Total time', '%.4f'%stats.total_time, '总耗时'],
['Average Time', '%.4f'%stats.avg, '每个连接的平均耗时'],
['Fatest Time', '%.4f'%stats.min, '最小耗时'],
['Slowest Time', '%.4f'%stats.max, '最大耗时'],
['Amplitude', '%4f'%stats.amp, '最大耗时和最小耗时之差'],
['Stand deviation', '%.6f'%stats.stdev, '耗时标准差'],
['Request Per Second', '%d'%rps, '每秒的访问量']
]
results_table = AsciiTable(results_table_data, 'Rsults')
results_table.inner_row_border = True
print('\n')
print(results_table.table)
print('\r\r\n\n')
status_table_data = [
['Status Code', 'Items']
]
for code, items in self.status_code_counter.items():
status_table_data.append(['%d'%code, '%d'%len(items)])
status_table = AsciiTable(status_table_data, 'StausCode')
print(status_table.table)
开发者ID:smaty1,项目名称:ab,代码行数:29,代码来源:request.py
示例3: search
def search(substring, include_deleted, include_pending, include_external, include_system, **criteria):
"""Searches users matching some criteria"""
assert set(criteria.viewkeys()) == {'first_name', 'last_name', 'email', 'affiliation'}
criteria = {k: v for k, v in criteria.viewitems() if v is not None}
res = search_users(exact=(not substring), include_deleted=include_deleted, include_pending=include_pending,
external=include_external, allow_system_user=include_system, **criteria)
if not res:
print(cformat('%{yellow}No results found'))
return
elif len(res) > 100:
click.confirm('{} results found. Show them anyway?'.format(len(res)), abort=True)
users = sorted((u for u in res if isinstance(u, User)), key=lambda x: (x.first_name.lower(), x.last_name.lower(),
x.email))
externals = sorted((ii for ii in res if isinstance(ii, IdentityInfo)),
key=lambda x: (_safe_lower(x.data.get('first_name')), _safe_lower(x.data.get('last_name')),
_safe_lower(x.data['email'])))
if users:
table_data = [['ID', 'First Name', 'Last Name', 'Email', 'Affiliation']]
for user in users:
table_data.append([unicode(user.id), user.first_name, user.last_name, user.email, user.affiliation])
table = AsciiTable(table_data, cformat('%{white!}Users%{reset}'))
table.justify_columns[0] = 'right'
print(table.table)
if externals:
if users:
print()
table_data = [['First Name', 'Last Name', 'Email', 'Affiliation', 'Source', 'Identifier']]
for ii in externals:
data = ii.data
table_data.append([data.get('first_name', ''), data.get('last_name', ''), data['email'],
data.get('affiliation', '-'), ii.provider.name, ii.identifier])
table = AsciiTable(table_data, cformat('%{white!}Externals%{reset}'))
print(table.table)
开发者ID:ThiefMaster,项目名称:indico,代码行数:33,代码来源:user.py
示例4: list
def list(self, name: str, running: bool, available: bool):
"""
Get running/available listeners
Usage: list [<name>] [--running] [--available] [-h]
Arguments:
name filter by listener name
Options:
-h, --help Show dis
-r, --running List running listeners
-a, --available List available listeners
"""
table_data = [
["Name", "Description"]
]
for l in self.loaded:
table_data.append([l.name, l.description])
table = AsciiTable(table_data, title="Available")
table.inner_row_border = True
print(table.table)
table_data = [
["Type", "Name", "URL"]
]
for l in self.listeners:
table_data.append([l.name, l["Name"], f"https://{l['BindIP']}:{l['Port']}"])
table = AsciiTable(table_data, title="Running")
table.inner_row_border = True
print(table.table)
开发者ID:vaginessa,项目名称:SILENTTRINITY,代码行数:34,代码来源:listeners.py
示例5: print_table
def print_table(self, data, title=None):
print ""
table = AsciiTable(data)
if title:
table.title = title
print table.table
print ""
开发者ID:0xe7,项目名称:CrackMapExec,代码行数:7,代码来源:cmedb.py
示例6: order_summary
def order_summary(entry, exit, commission):
data = []
if 'stop_price' in entry:
data.append(
['%(action)s %(quantity)s %(ticker)s STOP $%(stop_price).2f LIMIT' % entry.as_dict(),
pf(entry.price),
Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission)))]
)
else:
data.append(
['%(action)s %(quantity)s %(ticker)s LIMIT' % entry.as_dict(),
pf(entry.price),
Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission)))]
)
data.extend([
['50% Target', pf(half_target_price(entry, exit)), '+%s' % pf(half_target_profit(entry, exit, commission))],
['Target', pf(exit.target_price), '+%s' % pf(target_profit(entry, exit, commission))],
['Profit', '', Color('{green}+%s{/green}' % pf(total_profit(entry, exit, commission)))],
['Stop loss', pf(exit.stop_price), Color('{hired}-%s{/red}' % pf(risk(entry, exit, commission)))],
['Risk/Reward', '', Color('{%(color)s}%(risk_reward).1f to 1{/%(color)s}' % {
'risk_reward': risk_reward(entry, exit, commission),
'color': 'green' if risk_reward(entry, exit, commission) >= 3 else 'hired'
})],
])
table = AsciiTable(data)
table.inner_column_border = False
print(table.table)
开发者ID:briancappello,项目名称:PyTradeLib,代码行数:28,代码来源:trade.py
示例7: test_attributes
def test_attributes():
"""Test with different attributes."""
table_data = [
['Name', 'Color', 'Type'],
['Avocado', 'green', 'nut'],
['Tomato', 'red', 'fruit'],
['Lettuce', 'green', 'vegetable'],
]
table = AsciiTable(table_data)
assert 31 == max(len(r) for r in table.table.splitlines())
assert 31 == table.table_width
table.outer_border = False
assert 29 == max(len(r) for r in table.table.splitlines())
assert 29 == table.table_width
table.inner_column_border = False
assert 27 == max(len(r) for r in table.table.splitlines())
assert 27 == table.table_width
table.padding_left = 0
assert 24 == max(len(r) for r in table.table.splitlines())
assert 24 == table.table_width
table.padding_right = 0
assert 21 == max(len(r) for r in table.table.splitlines())
assert 21 == table.table_width
开发者ID:aleivag,项目名称:terminaltables,代码行数:28,代码来源:test_table_width_ok.py
示例8: view_services
def view_services(filterquery=None):
"""Prints out list of services and its relevant information"""
table = []
table.append(["Service Name", "Stacks", "Containers", "Parent S", "Child S", "Endpoints" ])
if filterquery:
services = filterquery.all()
#services = session.query(filterquery).all()
else:
services = session.query(Service).all()
if not services:
print "No services met the search"
return
for service in services:
state = service.get_state()
parents = [p['parent'] for p in state['parent']]
children = [c['child'] for c in state['childs']]
cs = []
for stack in state['stacks']:
for i, container in enumerate(stack['container']):
endpoint = service.tree_on_stack_pointer(i)
if endpoint:
cs.append("%s:%s:%s" % (container['name'], container['version'], endpoint.name))
else:
cs.append("%s:%s" % (container['name'], container['version']))
#cs.extend(["%s:%s" % (c['name'],c['version']) for c in stack['container']])
table.append([str(state['name']),
"\n".join([ s['name'] for s in state['stacks'] if s]),
str("\n".join(cs)),
"\n".join(parents),
"\n".join(children),
"\n".join(state['endpoints'])])
t = AsciiTable(table)
t.inner_row_border = True
print t.table
开发者ID:larhauga,项目名称:cmanage,代码行数:35,代码来源:basefunc.py
示例9: home_office
def home_office(ctx, year=CURRENT_YEAR):
"""
Show home office expenses.
"""
ss = open_spreadsheet('Home Office %s' % year)
worksheet = ss.worksheet('Monthly fees')
categories = defaultdict(Decimal)
for row in worksheet.get_all_records():
categories['hoa assessments'] += get_decimal(row['hoa assessments'])
categories['homeowners insurance'] += get_decimal(row['homeowners insurance'])
categories['mortgage'] += get_decimal(row['mortgage'])
categories['utilities (gas & electric)'] += \
get_decimal(row['electric']) + get_decimal(row['gas'])
data = [(k.capitalize(), v) for k, v in categories.items()]
data += [
(f'Total for {year}', sum(categories.values())),
(f'Office rent for {year}', sum(categories.values()) / 4),
('Repairs & maintenance', get_rm_total(ss)),
]
table = AsciiTable(data, 'Home office')
table.inner_heading_row_border = False
print(table.table)
开发者ID:feihong,项目名称:gss-meta,代码行数:27,代码来源:tasks.py
示例10: run
def run(self):
self.print_banner()
self.print_help()
while True:
command = self.input()
if command == 'addcert':
count = self.manager.command_addcert()
print "Successfully added %s certificates" % count
elif command == 'settings':
print SETTINGS
elif command == 'help':
self.print_banner()
self.print_help()
elif command == 'report':
rows, week_start, week_end, total = self.manager.command_report()
table = AsciiTable(rows, 'Certificates obtained %s-%s' % (week_start, week_end))
table.outer_border = False
print table.table
print "\nTotal certificates obtained: %s" % total
elif command == 'delete':
self.manager.command_delete()
elif command == 'exit':
return 0
else:
pass
开发者ID:mbs-dev,项目名称:certman,代码行数:32,代码来源:__init__.py
示例11: live
async def live(network, channel, message):
streams = await network.application.TwitchAPI.live()
headers = ['Streamer', 'Game', 'Viewers', 'Uptime']
out = [headers,]
now = datetime.datetime.utcnow()
for stream in streams:
started = datetime.datetime.strptime(stream['created_at'],'%Y-%m-%dT%H:%M:%SZ')
hours = (now-started).seconds // 3600
minutes = ( (now-started).seconds // 60 ) % 60
oneline = '{} has been live for {}:{}, now playing {} w/ {} viewers.\n'.format(
stream['channel']['display_name'],
hours,
minutes,
stream['game'],
stream['viewers']
)
oneline = [
stream['channel']['display_name'],
stream['game'],
str(stream['viewers']),
'{}h{}m'.format(hours,minutes),
]
out.append(oneline)
table = AsciiTable(out)
for i in range(len(out[0])):
table.justify_columns[i] = 'center'
await network.send_message(channel, '\n`{}`'.format(table.table))
开发者ID:,项目名称:,代码行数:35,代码来源:
示例12: table
def table(header, rows):
if not HAVE_TERMTAB:
print_error("Missing dependency, install terminaltables (`pip install terminaltables`)")
return
# TODO: Refactor this function, it is some serious ugly code.
content = [header] + rows
# Make sure everything is string
try:
content = [[a.replace('\t', ' ') for a in list(map(unicode, l))] for l in content]
except:
# Python3 way of doing it:
content = [[a.replace('\t', ' ') for a in list(map(str, l))] for l in content]
t = AsciiTable(content)
if not t.ok:
longest_col = t.column_widths.index(max(t.column_widths))
max_length_col = t.column_max_width(longest_col)
if max_length_col > 0:
for i, content in enumerate(t.table_data):
if len(content[longest_col]) > max_length_col:
temp = ''
for l in content[longest_col].splitlines():
if len(l) > max_length_col:
temp += '\n'.join(textwrap.wrap(l, max_length_col)) + '\n'
else:
temp += l + '\n'
content[longest_col] = temp.strip()
t.table_data[i] = content
return t.table
开发者ID:chubbymaggie,项目名称:viper,代码行数:31,代码来源:out.py
示例13: test_single_line
def test_single_line():
"""Test single-lined cells."""
table_data = [
['Name', 'Color', 'Type'],
['Avocado', 'green', 'nut'],
['Tomato', 'red', 'fruit'],
['Lettuce', 'green', 'vegetable'],
['Watermelon', 'green'],
[],
]
table = AsciiTable(table_data, 'Example')
table.inner_footing_row_border = True
table.justify_columns[0] = 'left'
table.justify_columns[1] = 'center'
table.justify_columns[2] = 'right'
actual = table.table
expected = (
'+Example-----+-------+-----------+\n'
'| Name | Color | Type |\n'
'+------------+-------+-----------+\n'
'| Avocado | green | nut |\n'
'| Tomato | red | fruit |\n'
'| Lettuce | green | vegetable |\n'
'| Watermelon | green | |\n'
'+------------+-------+-----------+\n'
'| | | |\n'
'+------------+-------+-----------+'
)
assert actual == expected
开发者ID:Robpol86,项目名称:terminaltables,代码行数:30,代码来源:test_ascii_table.py
示例14: print_download_item
def print_download_item(self, item, ascii_table):
dimensions = get_max_dimensions(ascii_table)
title = ""
for line in textwrap.wrap(
item.podcast.title,
dimensions[0][0],
initial_indent=' ',
subsequent_indent=' '):
title += line + "\n"
summ = ""
for line in textwrap.wrap(
item.summary,
dimensions[0][1],
initial_indent=' ',
subsequent_indent=' '):
summ += line + "\n"
if ascii_table:
ascii_table.table_data.append([title, summ])
print(ascii_table_last(ascii_table))
return ascii_table
else:
table_headers = [['title', 'summary']]
table_data = [[title, summ]]
ascii_table = AsciiTable(table_headers + table_data)
ascii_table.inner_row_border = True
print(ascii_table.table)
return ascii_table
开发者ID:bantonj,项目名称:podcli,代码行数:28,代码来源:podcli.py
示例15: print_table
def print_table(table_data):
table = AsciiTable(table_data)
table.inner_row_border = True
if table_data[:1] in ([['TITLE', 'IMDB RATING']],
[['TITLE', 'TOMATO RATING']]):
table.justify_columns[1] = 'center'
print("\n")
print(table.table)
开发者ID:iCHAIT,项目名称:moviemon,代码行数:8,代码来源:moviemon.py
示例16: show_license
def show_license(self):
licenses = self.metascan.get_license()
details = []
for lic in licenses.json().iteritems():
details.append([str(lic[0]), str(lic[1])])
table = AsciiTable(details, "Licenses")
table.inner_heading_row_border = False
print table.table
开发者ID:kovacsbalu,项目名称:viper-metascan,代码行数:8,代码来源:ms4.py
示例17: show_workflows
def show_workflows(self):
details = []
workflows = self.metascan.get_workflows()
for wf in workflows.json():
details.append([wf["name"]])
table = AsciiTable(details, "Workflows")
table.inner_heading_row_border = False
print table.table
开发者ID:kovacsbalu,项目名称:viper-metascan,代码行数:8,代码来源:ms4.py
示例18: frameTable
def frameTable():
frameTableP1 = [
[],['Frame#', 'Process#', 'Page#'],
[('\n'.join(map(str,range(16)))),('\n'.join(map(str,[j[1][0] for j in zipFrame]))),
(('\n'.join(map(str,[l[1][1] for l in zipFrame]))))]
]
table1 = AsciiTable(frameTableP1)
table1.title='--------FRAME TABLE'
print table1.table
开发者ID:dlombardi91,项目名称:LRUpagedVM,代码行数:9,代码来源:proj3.py
示例19: pTable4
def pTable4():
####process table p4
pageTableP4 = [[],
['Page #', 'Frame#'],
[('\n'.join(map(str,newP4))),
('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P4:' ]))))]
]
table4 = AsciiTable(pageTableP4)
table4.title='---4 Page Table'
print table4.table
开发者ID:dlombardi91,项目名称:LRUpagedVM,代码行数:11,代码来源:proj3.py
示例20: pTable1
def pTable1():
####process table p1
pageTableP1 = [[],
['Page #', 'Frame#'],
[('\n'.join(map(str,newP1))),
('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P1:' ]))))]
]
table = AsciiTable(pageTableP1)
table.title='---P1 Page Table'
print table.table
开发者ID:dlombardi91,项目名称:LRUpagedVM,代码行数:11,代码来源:proj3.py
注:本文中的terminaltables.AsciiTable类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论