Python pprint.pformat() Examples

The following are 30 code examples of pprint.pformat(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pprint , or try the search function .
Example #1
Source File: exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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),
        ) 
Example #2
Source File: engine.py    From Matrix-NEB with Apache License 2.0 6 votes vote down vote up
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)) 
Example #3
Source File: exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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),
        ) 
Example #4
Source File: ssl_servers.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #6
Source File: account_data.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #7
Source File: utils.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj) 
Example #8
Source File: widgets.py    From core with MIT License 5 votes vote down vote up
def on_copy_raw(self):
        """Copy raw version data to clipboard

        The data is string formatted with `pprint.pformat`.

        """
        raw = self.data.get("raw", None)
        if not raw:
            return

        raw_text = pprint.pformat(raw)
        clipboard = QtWidgets.QApplication.clipboard()
        clipboard.setText(raw_text) 
Example #9
Source File: information.py    From bot with MIT License 5 votes vote down vote up
def raw(self, ctx: Context, *, message: Message, json: bool = False) -> None:
        """Shows information about the raw API response."""
        # I *guess* it could be deleted right as the command is invoked but I felt like it wasn't worth handling
        # doing this extra request is also much easier than trying to convert everything back into a dictionary again
        raw_data = await ctx.bot.http.get_message(message.channel.id, message.id)

        paginator = Paginator()

        def add_content(title: str, content: str) -> None:
            paginator.add_line(f'== {title} ==\n')
            # replace backticks as it breaks out of code blocks. Spaces seemed to be the most reasonable solution.
            # we hope it's not close to 2000
            paginator.add_line(content.replace('```', '`` `'))
            paginator.close_page()

        if message.content:
            add_content('Raw message', message.content)

        transformer = pprint.pformat if json else self.format_fields
        for field_name in ('embeds', 'attachments'):
            data = raw_data[field_name]

            if not data:
                continue

            total = len(data)
            for current, item in enumerate(data, start=1):
                title = f'Raw {field_name} ({current}/{total})'
                add_content(title, transformer(item))

        for page in paginator.pages:
            await ctx.send(page) 
Example #10
Source File: expectations.py    From olympe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return pprint.pformat({self.expected_message.FullName: self.expected_args}) 
Example #11
Source File: expectations.py    From olympe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return pprint.pformat({self.expected_message.FullName: self.expected_args}) 
Example #12
Source File: utils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def partial_compare(val1, val2, *, indent=0):
    """Do a partial comparison between the given values.

    For dicts, keys in val2 are checked, others are ignored.
    For lists, entries at the positions in val2 are checked, others ignored.
    For other values, == is used.

    This happens recursively.
    """
    print_i("Comparing", indent)
    print_i(pprint.pformat(val1), indent + 1)
    print_i("|---- to ----", indent)
    print_i(pprint.pformat(val2), indent + 1)

    if val2 is Ellipsis:
        print_i("Ignoring ellipsis comparison", indent, error=True)
        return PartialCompareOutcome()
    elif type(val1) != type(val2):  # pylint: disable=unidiomatic-typecheck
        outcome = PartialCompareOutcome(
            "Different types ({}, {}) -> False".format(type(val1).__name__,
                                                       type(val2).__name__))
        print_i(outcome.error, indent, error=True)
        return outcome

    handlers = {
        dict: _partial_compare_dict,
        list: _partial_compare_list,
        float: _partial_compare_float,
        str: _partial_compare_str,
    }

    for typ, handler in handlers.items():
        if isinstance(val2, typ):
            print_i("|======= Comparing as {}".format(typ.__name__), indent)
            outcome = handler(val1, val2, indent=indent)
            break
    else:
        print_i("|======= Comparing via ==", indent)
        outcome = _partial_compare_eq(val1, val2, indent=indent)
    print_i("---> {}".format(outcome), indent)
    return outcome 
Example #13
Source File: test_resolvers.py    From tornado-zh with MIT License 5 votes vote down vote up
def main():
    args = parse_command_line()

    if not args:
        args = ['localhost', 'www.google.com',
                'www.facebook.com', 'www.dropbox.com']

    resolvers = [Resolver(), ThreadedResolver()]

    if twisted is not None:
        from tornado.platform.twisted import TwistedResolver
        resolvers.append(TwistedResolver())

    if pycares is not None:
        from tornado.platform.caresresolver import CaresResolver
        resolvers.append(CaresResolver())

    family = {
        'unspec': socket.AF_UNSPEC,
        'inet': socket.AF_INET,
        'inet6': socket.AF_INET6,
        }[options.family]

    for host in args:
        print('Resolving %s' % host)
        for resolver in resolvers:
            addrinfo = yield resolver.resolve(host, 80, family)
            print('%s: %s' % (resolver.__class__.__name__,
                              pprint.pformat(addrinfo)))
        print() 
Example #14
Source File: drone.py    From olympe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _connected_cb(self, _arsdk_device, arsdk_device_info, _user_data):
        """
        Notify connection completion.
        """
        device_name = od.string_cast(arsdk_device_info.contents.name)
        if self._device_name is None:
            self._device_name = device_name
            if self._name is None:
                self.logger = getLogger(
                    "olympe.drone.{}".format(self._device_name))
        self.logger.info("Connected to device: {}".format(device_name))
        json_info = od.string_cast(arsdk_device_info.contents.json)
        try:
            self._controller_state.device_conn_status.device_infos["json"] = \
                json.loads(json_info)
            self.logger.info(
                '%s' % pprint.pformat(self._controller_state.device_conn_status.device_infos))
        except ValueError:
            self.logger.error(
                'json contents cannot be parsed: {}'.format(json_info))

        self._controller_state.device_conn_status.connected = True

        if not self._is_skyctrl and self._media_autoconnect:
            media_hostname = self._ip_addr_str
            if self._media is not None:
                self._media.shutdown()
                self._media = None
            self._media = Media(
                media_hostname,
                name=self._name,
                device_name=self._device_name,
                scheduler=self._scheduler
            )
            self._media.async_connect()
        if self._connect_future is not None:
            self._connect_future.set_result(True) 
Example #15
Source File: payload_outbox.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #16
Source File: account_notifications_email_settings.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #17
Source File: account_notifications.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #18
Source File: account_notifications_slack_settings.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #19
Source File: account_notifications_sms_settings.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #20
Source File: account_settings_send_fax.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #21
Source File: account_notifications_email_settings_attachments.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #22
Source File: file.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #23
Source File: account.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #24
Source File: payload_fax_modification.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #25
Source File: binary.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #26
Source File: error.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #27
Source File: account_notifications_push_settings.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #28
Source File: account_notifications_blacklist.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #29
Source File: number.py    From faxplus-python with MIT License 5 votes vote down vote up
def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict()) 
Example #30
Source File: automate.py    From aospy with Apache License 2.0 5 votes vote down vote up
def _print_suite_summary(calc_suite_specs):
    """Print summary of requested calculations."""
    return ('\nRequested aospy calculations:\n' +
            pprint.pformat(calc_suite_specs) + '\n')