MCPcopy Index your code
hub / github.com/google/python-fire / SafeText

Function SafeText

fire/console/console_attr.py:714–754  ·  view source on GitHub ↗

br"""Converts the data to a text string compatible with the given encoding. This works the same way as Decode() below except it guarantees that any characters in the resulting text string can be re-encoded using the given encoding (or GetConsoleAttr().GetEncoding() if None is given). This mea

(data, encoding=None, escape=True)

Source from the content-addressed store, hash-verified

712
713
714def SafeText(data, encoding=None, escape=True):
715 br"""Converts the data to a text string compatible with the given encoding.
716
717 This works the same way as Decode() below except it guarantees that any
718 characters in the resulting text string can be re-encoded using the given
719 encoding (or GetConsoleAttr().GetEncoding() if None is given). This means
720 that the string will be safe to print to sys.stdout (for example) without
721 getting codec exceptions if the user's terminal doesn't support the encoding
722 used by the source of the text.
723
724 Args:
725 data: Any bytes, string, or object that has str() or unicode() methods.
726 encoding: The encoding name to ensure compatibility with. Defaults to
727 GetConsoleAttr().GetEncoding().
728 escape: Replace unencodable characters with a \uXXXX or \xXX equivalent if
729 True. Otherwise replace unencodable characters with an appropriate unknown
730 character, '?' for ASCII, and the unicode unknown replacement character
731 \uFFFE for unicode.
732
733 Returns:
734 A text string representation of the data, but modified to remove any
735 characters that would result in an encoding exception with the target
736 encoding. In the worst case, with escape=False, it will contain only ?
737 characters.
738 """
739 if data is None:
740 return 'None'
741 encoding = encoding or GetConsoleAttr().GetEncoding()
742 string = encoding_util.Decode(data, encoding=encoding)
743
744 try:
745 # No change needed if the string encodes to the output encoding.
746 string.encode(encoding)
747 return string
748 except UnicodeError:
749 # The string does not encode to the output encoding. Encode it with error
750 # handling then convert it back into a text string (which will be
751 # guaranteed to only contain characters that can be encoded later.
752 return (string
753 .encode(encoding, 'backslashreplace' if escape else 'replace')
754 .decode(encoding))
755
756
757def EncodeToBytes(data):

Callers

nothing calls this directly

Calls 2

GetConsoleAttrFunction · 0.85
GetEncodingMethod · 0.80

Tested by

no test coverage detected