當前位置: 首頁>>代碼示例>>Python>>正文


Python pprint.pformat方法代碼示例

本文整理匯總了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)) 
開發者ID:rafasashi,項目名稱:razzy-spinner,代碼行數:19,代碼來源:util.py

示例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)) 
開發者ID:matrix-org,項目名稱:Matrix-NEB,代碼行數:23,代碼來源:engine.py

示例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) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:19,代碼來源:ssl_servers.py

示例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),
        ) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:26,代碼來源:exceptions.py

示例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') 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:6,代碼來源:automate.py

示例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))) 
開發者ID:spencerahill,項目名稱:aospy,代碼行數:17,代碼來源:data_loader.py

示例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" 
開發者ID:aploium,項目名稱:zmirror,代碼行數:13,代碼來源:utils.py

示例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 
開發者ID:aploium,項目名稱:zmirror,代碼行數:42,代碼來源:base_class.py

示例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]) 
開發者ID:francozappa,項目名稱:knob,代碼行數:43,代碼來源:es_tests.py

示例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 
開發者ID:frictionlessdata,項目名稱:goodtables-py,代碼行數:40,代碼來源:cli.py

示例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 
開發者ID:trufont,項目名稱:tfont,代碼行數:10,代碼來源:path.py

示例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)) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:13,代碼來源:case.py

示例13: __repr__

# 需要導入模塊: import pprint [as 別名]
# 或者: from pprint import pformat [as 別名]
def __repr__(self):
        return pprint.pformat(list(self)) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:4,代碼來源:mock.py

示例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) 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:41,代碼來源:test_case.py

示例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") 
開發者ID:OpenTrading,項目名稱:OpenTrader,代碼行數:14,代碼來源:ListenerThread.py


注:本文中的pprint.pformat方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。