How to use the humanfriendly.text.format function in humanfriendly

To help you get started, we’ve selected a few humanfriendly examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xolox / python-property-manager / property_manager / tests.py View on Github external
# Test that the sentence added for writable properties is present when applicable.
        assert self.property_type.writable == (WRITABLE_PROPERTY_NOTE in documentation)
        # Test that the sentence added for cached properties is present when applicable.
        assert self.property_type.cached == (CACHED_PROPERTY_NOTE in documentation)
        # Test that the sentence added for resettable properties is present when applicable.
        if self.is_resettable:
            assert self.is_cached == (RESETTABLE_CACHED_PROPERTY_NOTE in documentation)
            assert self.is_writable == (RESETTABLE_WRITABLE_PROPERTY_NOTE in documentation)
        else:
            assert RESETTABLE_CACHED_PROPERTY_NOTE not in documentation
            assert RESETTABLE_WRITABLE_PROPERTY_NOTE not in documentation
        # Test that the sentence added for required properties is present when applicable.
        required_property_note = format(REQUIRED_PROPERTY_NOTE, name='documented_property')
        assert self.property_type.required == (required_property_note in documentation)
        # Test that the sentence added for environment properties is present when applicable.
        environment_note = format(ENVIRONMENT_PROPERTY_NOTE, variable=self.property_type.environment_variable)
        assert bool(self.property_type.environment_variable) == (environment_note in documentation)
github xolox / python-executor / executor / __init__.py View on Github external
def format_error_message(self, message, *args, **kw):
        """
        Add the command's captured standard output and/or error to an error message.

        Refer to :func:`~humanfriendly.text.compact()` for details on argument
        handling. The :func:`get_decoded_output()` method is used to try to
        decode the output without raising exceptions.
        """
        message = format(message, *args, **kw)
        if self.buffered:
            stdout = self.get_decoded_output('stdout')
            stderr = self.get_decoded_output('stderr')
            if stdout and self.merge_streams:
                message += format("\n\nStandard output / error (merged):\n%s", stdout)
            elif stdout:
                message += format("\n\nStandard output:\n%s", stdout)
            if stderr and not self.merge_streams:
                message += format("\n\nStandard error:\n%s", stderr)
        return message
github xolox / python-property-manager / property_manager / __init__.py View on Github external
def compose_usage_notes(self):
        """
        Get a description of the property's semantics to include in its documentation.

        :returns: A list of strings describing the semantics of the
                  :class:`custom_property` in reStructuredText_ format with
                  Sphinx_ directives.

        .. _reStructuredText: https://en.wikipedia.org/wiki/ReStructuredText
        .. _Sphinx: http://sphinx-doc.org/
        """
        template = DYNAMIC_PROPERTY_NOTE if self.dynamic else CUSTOM_PROPERTY_NOTE
        cls = custom_property if self.dynamic else self.__class__
        dotted_path = "%s.%s" % (cls.__module__, cls.__name__)
        notes = [format(template, name=self.__name__, type=dotted_path)]
        if self.environment_variable:
            notes.append(format(ENVIRONMENT_PROPERTY_NOTE, variable=self.environment_variable))
        if self.required:
            notes.append(format(REQUIRED_PROPERTY_NOTE, name=self.__name__))
        if self.key:
            notes.append(KEY_PROPERTY_NOTE)
        if self.writable:
            notes.append(WRITABLE_PROPERTY_NOTE)
        if self.cached:
            notes.append(CACHED_PROPERTY_NOTE)
        if self.resettable:
            if self.cached:
                notes.append(RESETTABLE_CACHED_PROPERTY_NOTE)
            else:
                notes.append(RESETTABLE_WRITABLE_PROPERTY_NOTE)
        return notes
github xolox / python-humanfriendly / humanfriendly / terminal.py View on Github external
:param stream: The file-like object to write to (a value like
                   :data:`sys.stdout` or :data:`sys.stderr`).
    :param text: The text to write to the stream (a string).
    :param args: Refer to :func:`~humanfriendly.text.format()`.
    :param kw: Refer to :func:`~humanfriendly.text.format()`.

    Renders the text using :func:`~humanfriendly.text.format()` and writes it
    to the given stream. If an :exc:`~exceptions.UnicodeEncodeError` is
    encountered in doing so, the text is encoded using :data:`DEFAULT_ENCODING`
    and the write is retried. The reasoning behind this rather blunt approach
    is that it's preferable to get output on the command line in the wrong
    encoding then to have the Python program blow up with a
    :exc:`~exceptions.UnicodeEncodeError` exception.
    """
    text = format(text, *args, **kw)
    try:
        stream.write(text)
    except UnicodeEncodeError:
        stream.write(codecs.encode(text, DEFAULT_ENCODING))
github xolox / python-humanfriendly / humanfriendly / __init__.py View on Github external
- Other strings raise an exception.

                  Other Python values are coerced using :func:`bool()`.
    :returns: A proper boolean value.
    :raises: :exc:`exceptions.ValueError` when the value is a string but
             cannot be coerced with certainty.
    """
    if is_string(value):
        normalized = value.strip().lower()
        if normalized in ('1', 'yes', 'true', 'on'):
            return True
        elif normalized in ('0', 'no', 'false', 'off', ''):
            return False
        else:
            msg = "Failed to coerce string to boolean! (%r)"
            raise ValueError(format(msg, value))
    else:
        return bool(value)
github xolox / python-executor / executor / cli.py View on Github external
def __init__(self, command, timeout):
        """
        Initialize a :class:`CommandTimedOut` object.

        :param command: The command that timed out (an
                        :class:`~executor.ExternalCommand` object).
        :param timeout: The timeout that was exceeded (a number).
        """
        super(CommandTimedOut, self).__init__(
            command=command,
            error_message=format(
                "External command exceeded timeout of %s: %s",
                format_timespan(timeout),
                quote(command.command_line),
            ),
github xolox / python-humanfriendly / humanfriendly / __init__.py View on Github external
:param value: An :class:`int`, :class:`float` or
                  :class:`datetime.timedelta` object.
    :returns: An :class:`int` or :class:`float` value.

    When `value` is a :class:`datetime.timedelta` object the
    :func:`~datetime.timedelta.total_seconds()` method is called.
    On Python 2.6 this method is not available so it is emulated.
    """
    if isinstance(value, datetime.timedelta):
        if hasattr(value, 'total_seconds'):
            return value.total_seconds()
        else:
            return (value.microseconds + (value.seconds + value.days * 24 * 3600) * 10**6) / 10**6
    if not isinstance(value, numbers.Number):
        msg = "Failed to coerce value to number of seconds! (%r)"
        raise ValueError(format(msg, value))
    return value