本文整理汇总了Python中pprint.pformat方法的典型用法代码示例。如果您正苦于以下问题:Python pprint.pformat方法的具体用法?Python pprint.pformat怎么用?Python pprint.pformat使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pprint
的用法示例。
在下文中一共展示了pprint.pformat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _validate_creds_file
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def _validate_creds_file(self, verbose=False):
"""Check validity of a credentials file."""
oauth1 = False
oauth1_keys = ['app_key', 'app_secret', 'oauth_token', 'oauth_token_secret']
oauth2 = False
oauth2_keys = ['app_key', 'app_secret', 'access_token']
if all(k in self.oauth for k in oauth1_keys):
oauth1 = True
elif all(k in self.oauth for k in oauth2_keys):
oauth2 = True
if not (oauth1 or oauth2):
msg = 'Missing or incorrect entries in {}\n'.format(self.creds_file)
msg += pprint.pformat(self.oauth)
raise ValueError(msg)
elif verbose:
print('Credentials file "{}" looks good'.format(self.creds_file))
示例2: init_from_sync
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def init_from_sync(self, sync):
for room_id in sync["rooms"]["join"]:
# see if we know anything about these rooms
room = sync["rooms"]["join"][room_id]
self.state[room_id] = {}
try:
for state in room["state"]["events"]:
if state["type"] in self.types:
key = (state["type"], state["state_key"])
s = state
if self.content_only:
s = state["content"]
self.state[room_id][key] = s
except KeyError:
pass
log.debug(pprint.pformat(self.state))
示例3: do_GET
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def do_GET(self, send_body=True):
"""Serve a GET request."""
sock = self.rfile.raw._sock
context = sock.context
stats = {
'session_cache': context.session_stats(),
'cipher': sock.cipher(),
'compression': sock.compression(),
}
body = pprint.pformat(stats)
body = body.encode('utf-8')
self.send_response(200)
self.send_header("Content-type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if send_body:
self.wfile.write(body)
示例4: __unicode__
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def __unicode__(self):
essential_for_verbose = (
self.validator, self.validator_value, self.instance, self.schema,
)
if any(m is _unset for m in essential_for_verbose):
return self.message
pschema = pprint.pformat(self.schema, width=72)
pinstance = pprint.pformat(self.instance, width=72)
return self.message + textwrap.dedent("""
Failed validating %r in schema%s:
%s
On instance%s:
%s
""".rstrip()
) % (
self.validator,
_utils.format_as_index(list(self.relative_schema_path)[:-1]),
_utils.indent(pschema),
_utils.format_as_index(self.relative_path),
_utils.indent(pinstance),
)
示例5: _print_suite_summary
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def _print_suite_summary(calc_suite_specs):
"""Print summary of requested calculations."""
return ('\nRequested aospy calculations:\n' +
pprint.pformat(calc_suite_specs) + '\n')
示例6: _generate_file_set
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def _generate_file_set(self, var=None, start_date=None, end_date=None,
domain=None, intvl_in=None, dtype_in_vert=None,
dtype_in_time=None, intvl_out=None):
attempted_file_sets = []
for name in var.names:
file_set = self._input_data_paths_gfdl(
name, start_date, end_date, domain, intvl_in, dtype_in_vert,
dtype_in_time, intvl_out)
attempted_file_sets.append(file_set)
if all([os.path.isfile(filename) for filename in file_set]):
return file_set
raise IOError('Files for the var {0} cannot be located '
'using GFDL post-processing conventions. '
'Attempted using the following sets of paths:\n\n'
'{1}'.format(var, pprint.pformat(attempted_file_sets)))
示例7: rv_dmp
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def rv_dmp(rv):
"""
:type rv: Response
:rtype: str
"""
from pprint import pformat
dump = "\n------------- rv -------------\n"
dump += attributes(rv)
dump += "\n------------- rv.headers -------------\n"
dump += pformat(rv.headers.items())
dump += "\n------------- end dump -------------\n"
示例8: _dump
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def _dump(self, select='all'):
"""
:type select: Union[int, str]
:rtype: str
"""
from pprint import pformat
select = {
"all": "all",
1: "rv",
2: "rv2",
3: "rv3",
}[select]
dump = "\n------------- begin dump -------------"
dump += "\n------------- zmirror parse -------------\n"
dump += attributes(self.zmirror.parse)
if self.zmirror.parse.remote_response is not None:
dump += "\n------------- zmirror remote request -------------\n"
dump += attributes(self.zmirror.parse.remote_response.request)
dump += "\n------------- zmirror remote response -------------\n"
dump += attributes(self.zmirror.parse.remote_response)
for rv_name in ([select] if select != "all" else ["rv", "rv2", "rv3"]):
if not hasattr(self, rv_name):
continue
rv = getattr(self, rv_name) # type: Response
if not isinstance(rv, Response):
continue
dump += "\n------------- {} -------------\n".format(rv_name)
dump += attributes(rv)
dump += "\n------------- {}.headers -------------\n".format(rv_name)
dump += pformat(list(rv.headers.items()))
dump += "\n------------- end dump -------------\n"
return dump
示例9: test_Kc_prime_entropy2
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def test_Kc_prime_entropy2():
"""Fix L vary Kc Byte by Byte"""
zero = bytearray.fromhex('00000000000000000000000000000000')
almost_one = bytearray('\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff')
Kc = bytearray.fromhex('00001111222233334444555566667777')
# log.info('test_Kc_prime_entropy2 Kc : {}'.format(repr(Kc)))
L = 1
for l in range(2,17):
L = l
filename = 'kcs/L{}-00001111222233334444555566667777.txt'.format(L)
with open(filename, mode="w") as fp:
fp.write('test_Kc_prime_entropy2 Kc :{}\n'.format(repr(Kc)))
for j in range(16): # 0--15
rv = {}
zeros = []
almost_ones = []
BYTE_INDEX = j
for i in range(256): # 0..256
Kc[BYTE_INDEX] = i
# log.info('test_Kc_prime_entropy2 Kc[{}]: {}'.format(BYTE_INDEX, i))
rv[i] = Kc_to_Kc_prime(Kc, L)
if rv[i] == zero:
zeros.append(i)
elif rv[i] == almost_one:
almost_ones.append(i)
fp.write('test_Kc_prime_entropy2 BEGIN BYTE_INDEX: {}\n'.format(BYTE_INDEX))
# log.info('test_Kc_prime_entropy2 zeros : {}'.format(repr(zeros)))
fp.write('test_Kc_prime_entropy2 zeros : {}\n'.format(repr(zeros)))
# log.info('test_Kc_prime_entropy2 almost_ones : {}'.format(repr(almost_ones)))
fp.write('test_Kc_prime_entropy2 almost_ones : {}\n'.format(repr(almost_ones)))
rvp = pprint.pformat(rv, 4)
# log.info('test_Kc_prime_entropy2 Kc : {}'.format(rvp))
fp.write('test_Kc_prime_entropy2 Kc_prime : {}\n'.format(rvp))
fp.write('test_Kc_prime_entropy2 END BYTE_INDEX : {}\n\n'.format(BYTE_INDEX))
print('{} BYTE_INDEX {} zeros: {}, almost_ones: {}'.format(
filename, j, zeros, almost_ones))
# print('Output of: cat {}'.format(filename))
# call(["cat", filename])
示例10: _print_report
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def _print_report(report, output=None, json=False):
def secho(*args, **kwargs):
click.secho(file=output, *args, **kwargs)
if json:
return secho(json_module.dumps(report, indent=4))
color = 'green' if report['valid'] else 'red'
tables = report.pop('tables')
warnings = report.pop('warnings')
secho('DATASET', bold=True)
secho('='*7, bold=True)
secho(pformat(report), fg=color, bold=True)
if warnings:
secho('-'*9, bold=True)
for warning in warnings:
secho('Warning: %s' % warning, fg='yellow')
for table_number, table in enumerate(tables, start=1):
secho('\nTABLE [%s]' % table_number, bold=True)
secho('='*9, bold=True)
color = 'green' if table['valid'] else 'red'
errors = table.pop('errors')
secho(pformat(table), fg=color, bold=True)
if errors:
secho('-'*9, bold=True)
for error in errors:
template = '[{row-number},{column-number}] [{code}] {message}'
substitutions = {
'row-number': error.get('row-number', '-'),
'column-number': error.get('column-number', '-'),
'code': error.get('code', '-'),
'message': error.get('message', '-'),
}
message = template.format(**substitutions)
secho(message)
# Main
示例11: __repr__
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def __repr__(self):
name = self.__class__.__name__
width = 80 - len(name) - 2
return "%s(%s)" % (
name, pprint.pformat(self._points, width=width).replace(
"\n ", "\n " + " " * len(name))) # pad indent
# __setattr__ not needed thus far
示例12: assertDictEqual
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def assertDictEqual(self, d1, d2, msg=None):
self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
示例13: __repr__
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def __repr__(self):
return pprint.pformat(list(self))
示例14: testAssertSequenceEqualMaxDiff
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def testAssertSequenceEqualMaxDiff(self):
self.assertEqual(self.maxDiff, 80*8)
seq1 = 'a' + 'x' * 80**2
seq2 = 'b' + 'x' * 80**2
diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
# the +1 is the leading \n added by assertSequenceEqual
omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,)
self.maxDiff = len(diff)//2
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) < len(diff))
self.assertIn(omitted, msg)
self.maxDiff = len(diff) * 2
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) > len(diff))
self.assertNotIn(omitted, msg)
self.maxDiff = None
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) > len(diff))
self.assertNotIn(omitted, msg)
示例15: vPprint
# 需要导入模块: import pprint [as 别名]
# 或者: from pprint import pformat [as 别名]
def vPprint(self, sMsgType, sMsg=None, sPrefix="INFO: "):
if sMsgType == 'get':
sys.stdout.write("INFO: bPprint" +repr(self.bPprint) + "\n")
elif sMsgType == 'set':
self.bPprint = bool(sMsg)
elif sMsgType in self.lHide:
pass
elif self.bPprint and sMsg:
# may need more info here - chart and sMark
sys.stdout.write(sPrefix +sMsgType +" = " +pformat(sMsg) +"\n")
else:
sys.stdout.write(sPrefix +sMsgType +" = " +repr(sMsg) +"\n")