Skip to content

robot.utils.encoding

console_decode

console_decode(string, encoding=CONSOLE_ENCODING)

Decodes bytes from console encoding to Unicode.

Uses the system console encoding by default, but that can be configured using the encoding argument. In addition to the normal encodings, it is possible to use case-insensitive values CONSOLE and SYSTEM to use the system console and system encoding, respectively.

If string is already Unicode, it is returned as-is.

Source code in src/robot/utils/encoding.py
def console_decode(string, encoding=CONSOLE_ENCODING):
    """Decodes bytes from console encoding to Unicode.

    Uses the system console encoding by default, but that can be configured
    using the `encoding` argument. In addition to the normal encodings,
    it is possible to use case-insensitive values `CONSOLE` and `SYSTEM` to
    use the system console and system encoding, respectively.

    If `string` is already Unicode, it is returned as-is.
    """
    if is_string(string):
        return string
    encoding = {'CONSOLE': CONSOLE_ENCODING,
                'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding)
    try:
        return string.decode(encoding)
    except UnicodeError:
        return safe_str(string)

console_encode

1
2
3
4
5
6
7
console_encode(
    string,
    encoding=None,
    errors="replace",
    stream=__stdout__,
    force=False,
)

Encodes the given string so that it can be used in the console.

If encoding is not given, determines it based on the given stream and system configuration. In addition to the normal encodings, it is possible to use case-insensitive values CONSOLE and SYSTEM to use the system console and system encoding, respectively.

Decodes bytes back to Unicode by default, because Python 3 APIs in general work with strings. Use force=True if that is not desired.

Source code in src/robot/utils/encoding.py
def console_encode(string, encoding=None, errors='replace', stream=sys.__stdout__,
                   force=False):
    """Encodes the given string so that it can be used in the console.

    If encoding is not given, determines it based on the given stream and system
    configuration. In addition to the normal encodings, it is possible to use
    case-insensitive values `CONSOLE` and `SYSTEM` to use the system console
    and system encoding, respectively.

    Decodes bytes back to Unicode by default, because Python 3 APIs in general
    work with strings. Use `force=True` if that is not desired.
    """
    if not is_string(string):
        string = safe_str(string)
    if encoding:
        encoding = {'CONSOLE': CONSOLE_ENCODING,
                    'SYSTEM': SYSTEM_ENCODING}.get(encoding.upper(), encoding)
    else:
        encoding = _get_console_encoding(stream)
    if encoding.upper() != 'UTF-8':
        encoded = string.encode(encoding, errors)
        return encoded if force else encoded.decode(encoding)
    return string.encode(encoding, errors) if force else string