| 1 |
"""Utilities for handling encoded input/output streams. |
| 2 |
|
| 3 |
Includes codec alias registration and automatic encoding/decoding for standard |
| 4 |
streams. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import codecs |
| 10 |
import os |
| 11 |
import sys |
| 12 |
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO |
| 13 |
|
| 14 |
from DisplayCAL.encoding import get_encoding |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from collections.abc import Iterator |
| 18 |
|
| 19 |
if sys.version_info >= (3, 11): |
| 20 |
from typing import Self |
| 21 |
else: |
| 22 |
from typing_extensions import Self |
| 23 |
|
| 24 |
|
| 25 |
_codecs = {} |
| 26 |
_stdio = {} |
| 27 |
|
| 28 |
|
| 29 |
def codec_register_alias(alias: str, name: str) -> None: |
| 30 |
"""Register an alias for encoding 'name'. |
| 31 |
|
| 32 |
Args: |
| 33 |
alias (str): The alias to register. |
| 34 |
name (str): The name of the encoding to alias. |
| 35 |
""" |
| 36 |
_codecs[alias] = codecs.CodecInfo( |
| 37 |
name=alias, |
| 38 |
encode=codecs.getencoder(name), |
| 39 |
decode=codecs.getdecoder(name), |
| 40 |
incrementalencoder=codecs.getincrementalencoder(name), |
| 41 |
incrementaldecoder=codecs.getincrementaldecoder(name), |
| 42 |
streamwriter=codecs.getwriter(name), |
| 43 |
streamreader=codecs.getreader(name), |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
def conditional_decode( |
| 48 |
text: bytes | str, encoding: str = "UTF-8", errors: str = "strict" |
| 49 |
) -> str: |
| 50 |
"""Decode text if not unicode. |
| 51 |
|
| 52 |
Args: |
| 53 |
text (bytes | str): The text to decode. |
| 54 |
encoding (str): The encoding to use. Defaults to 'UTF-8'. |
| 55 |
errors (str): The error handling scheme to use. Defaults to 'strict'. |
| 56 |
|
| 57 |
Returns: |
| 58 |
str: The decoded text. |
| 59 |
""" |
| 60 |
if not isinstance(text, str): |
| 61 |
text = text.decode(encoding, errors) |
| 62 |
return text |
| 63 |
|
| 64 |
|
| 65 |
def conditional_encode( |
| 66 |
text: str, encoding: str = "UTF-8", errors: str = "strict" |
| 67 |
) -> bytes: |
| 68 |
"""Encode text if unicode. |
| 69 |
|
| 70 |
Args: |
| 71 |
text (str): The text to encode. |
| 72 |
encoding (str): The encoding to use. Defaults to 'UTF-8'. |
| 73 |
errors (str): The error handling scheme to use. Defaults to 'strict'. |
| 74 |
""" |
| 75 |
if isinstance(text, str): |
| 76 |
text = text.encode(encoding, errors) |
| 77 |
return text |
| 78 |
|
| 79 |
|
| 80 |
def encodestdio(encodings: None | dict = None, errors: None | dict = None) -> None: |
| 81 |
"""Wrap sys.stdin, sys.stdout, and sys.stderr with EncodedStream. |
| 82 |
|
| 83 |
After this function is called, Unicode strings written to stdout/stderr are |
| 84 |
automatically encoded and strings read from stdin automatically decoded |
| 85 |
with the given encodings and error handling. |
| 86 |
|
| 87 |
encodings and errors can be a dict with mappings for stdin/stdout/stderr, |
| 88 |
e.g. encodings={'stdin': 'UTF-8', 'stdout': 'UTF-8', 'stderr': 'UTF-8'} |
| 89 |
or errors={'stdin': 'strict', 'stdout': 'replace', 'stderr': 'replace'} |
| 90 |
|
| 91 |
In the case of errors, stdin uses a default 'strict' error handling and |
| 92 |
stdout/stderr both use 'replace'. |
| 93 |
|
| 94 |
Args: |
| 95 |
encodings (None | dict, optional): A dictionary mapping stream names to |
| 96 |
encodings. Defaults to None, which uses the system default |
| 97 |
encoding. |
| 98 |
errors (None | dict, optional): A dictionary mapping stream names to |
| 99 |
error handling schemes. Defaults to None, which uses 'strict' for |
| 100 |
stdin and 'replace' for stdout/stderr. |
| 101 |
""" |
| 102 |
if not encodings: |
| 103 |
encodings = {"stdin": None, "stdout": None, "stderr": None} |
| 104 |
if not errors: |
| 105 |
errors = {"stdin": "strict", "stdout": "replace", "stderr": "replace"} |
| 106 |
for stream_name in set(list(encodings.keys()) + list(errors.keys())): |
| 107 |
stream = getattr(sys, stream_name) |
| 108 |
encoding = encodings.get(stream_name) |
| 109 |
if not encoding: |
| 110 |
encoding = get_encoding(stream) |
| 111 |
error_handling = errors.get(stream_name, "strict") |
| 112 |
if isinstance(stream, EncodedStream): |
| 113 |
stream.encoding = encoding |
| 114 |
stream.errors = error_handling |
| 115 |
else: |
| 116 |
setattr(sys, stream_name, EncodedStream(stream, encoding, error_handling)) |
| 117 |
|
| 118 |
|
| 119 |
def read(stream: BinaryIO | TextIO, size: int = -1) -> bytes: |
| 120 |
"""Read from stream. |
| 121 |
|
| 122 |
Uses os.read() if stream is a tty, stream.read() otherwise. |
| 123 |
|
| 124 |
Args: |
| 125 |
stream (BinaryIO | TextIO): The stream to read from. |
| 126 |
size (int): The number of bytes to read. Defaults to -1, which reads |
| 127 |
the entire stream. |
| 128 |
|
| 129 |
Returns: |
| 130 |
bytes: The bytes read from the stream. |
| 131 |
""" |
| 132 |
return os.read(stream.fileno(), size) if stream.isatty() else stream.read(size) |
| 133 |
|
| 134 |
|
| 135 |
def write(stream: BinaryIO | TextIO, data: bytes | str) -> None: |
| 136 |
"""Write to stream. |
| 137 |
|
| 138 |
Uses os.write() if stream is a tty, stream.write() otherwise. |
| 139 |
|
| 140 |
Args: |
| 141 |
stream (BinaryIO | TextIO): The stream to write to. |
| 142 |
data(bytes | str): The data to write to the stream. Should be bytes if |
| 143 |
the stream is a tty, or str if the stream is not a tty. |
| 144 |
""" |
| 145 |
if stream.isatty(): |
| 146 |
os.write(stream.fileno(), data) |
| 147 |
else: |
| 148 |
stream.write(data) |
| 149 |
|
| 150 |
|
| 151 |
class EncodedStream: |
| 152 |
"""Automatically encodes writes and decodes reads using the given encoding. |
| 153 |
|
| 154 |
This class also does error handling. Uses os.read() and os.write() for |
| 155 |
proper handling of unicode codepages for stdout/stderr under Windows. |
| 156 |
|
| 157 |
Args: |
| 158 |
stream (BinaryIO | TextIO): The stream to wrap (e.g., sys.stdin, |
| 159 |
sys.stdout, sys.stderr). |
| 160 |
encoding (str): The encoding to use for decoding reads and encoding |
| 161 |
writes. Defaults to 'UTF-8'. |
| 162 |
errors (str): The error handling scheme to use for decoding/encoding. |
| 163 |
Defaults to 'strict'. |
| 164 |
""" |
| 165 |
|
| 166 |
def __init__( |
| 167 |
self, stream: BinaryIO | TextIO, encoding: str = "UTF-8", errors: str = "strict" |
| 168 |
) -> None: |
| 169 |
self.stream = stream |
| 170 |
self.encoding = encoding |
| 171 |
self.errors = errors |
| 172 |
|
| 173 |
def __getattr__(self, name: str) -> Any: # noqa: ANN401 |
| 174 |
"""Get attributes from the stream or the EncodedStream itself. |
| 175 |
|
| 176 |
Args: |
| 177 |
name (str): The name of the attribute to get. |
| 178 |
""" |
| 179 |
return getattr(self.stream, name) |
| 180 |
|
| 181 |
def __iter__(self) -> Iterator[str]: |
| 182 |
"""Return an iterator over the lines in the stream.""" |
| 183 |
return iter(self.readlines()) |
| 184 |
|
| 185 |
def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401 |
| 186 |
"""Set attributes on the stream or the EncodedStream itself. |
| 187 |
|
| 188 |
Args: |
| 189 |
name (str): The name of the attribute to set. |
| 190 |
value (Any): The value to set the attribute to. |
| 191 |
""" |
| 192 |
if name == "softspace": |
| 193 |
setattr(self.stream, name, value) |
| 194 |
else: |
| 195 |
object.__setattr__(self, name, value) |
| 196 |
|
| 197 |
def __next__(self) -> str: |
| 198 |
"""Read the next line from the stream. |
| 199 |
|
| 200 |
Returns: |
| 201 |
str: The next line read from the stream, decoded. |
| 202 |
""" |
| 203 |
return self.readline() |
| 204 |
|
| 205 |
def read(self, size: int = -1) -> str: |
| 206 |
"""Read from the stream and decode it. |
| 207 |
|
| 208 |
Args: |
| 209 |
size (int): The number of bytes to read. Defaults to -1, which |
| 210 |
reads the entire stream. |
| 211 |
|
| 212 |
Returns: |
| 213 |
str: The decoded text read from the stream. |
| 214 |
""" |
| 215 |
return conditional_decode(read(self.stream, size), self.encoding, self.errors) |
| 216 |
|
| 217 |
def readline(self, size: int = -1) -> str: |
| 218 |
"""Read a single line from the stream and decode it. |
| 219 |
|
| 220 |
Args: |
| 221 |
size (int): The number of bytes to read. Defaults to -1, which |
| 222 |
reads the entire line. |
| 223 |
|
| 224 |
Returns: |
| 225 |
str: The decoded line read from the stream. |
| 226 |
""" |
| 227 |
return conditional_decode( |
| 228 |
self.stream.readline(size), self.encoding, self.errors |
| 229 |
) |
| 230 |
|
| 231 |
def readlines(self, size: int = -1) -> list[str]: |
| 232 |
"""Read lines from the stream and decode them. |
| 233 |
|
| 234 |
Args: |
| 235 |
size (int): The number of bytes to read. Defaults to -1, which |
| 236 |
reads all lines. |
| 237 |
|
| 238 |
Returns: |
| 239 |
list[str]: A list of decoded lines read from the stream. |
| 240 |
""" |
| 241 |
return [ |
| 242 |
conditional_decode(line, self.encoding, self.errors) |
| 243 |
for line in self.stream.readlines(size) |
| 244 |
] |
| 245 |
|
| 246 |
def xreadlines(self) -> Self: |
| 247 |
"""Return an iterator that reads lines from the stream. |
| 248 |
|
| 249 |
Returns: |
| 250 |
Iterator[str]: An iterator that yields lines from the stream. |
| 251 |
""" |
| 252 |
return self |
| 253 |
|
| 254 |
def write(self, text: str) -> None: |
| 255 |
"""Write text to the stream, encoding it if necessary. |
| 256 |
|
| 257 |
Args: |
| 258 |
text (str): The text to write to the stream. |
| 259 |
""" |
| 260 |
write(self.stream, conditional_encode(text, self.encoding, self.errors)) |
| 261 |
|
| 262 |
def writelines(self, lines: list[str]) -> None: |
| 263 |
"""Write a list of lines to the stream. |
| 264 |
|
| 265 |
Args: |
| 266 |
lines (list[str]): A list of strings to write to the stream. |
| 267 |
""" |
| 268 |
for line in lines: |
| 269 |
self.write(line) |
| 270 |
|
| 271 |
|
| 272 |
# Store references to original stdin/stdout/stderr |
| 273 |
for _stream_name in ("stdin", "stdout", "stderr"): |
| 274 |
_stream = getattr(sys, _stream_name) |
| 275 |
if isinstance(_stream, EncodedStream): |
| 276 |
_stdio[_stream_name] = _stream.stream |
| 277 |
else: |
| 278 |
_stdio[_stream_name] = _stream |
| 279 |
|
| 280 |
# Register codec aliases for codepages 65000 and 65001 |
| 281 |
codec_register_alias("65000", "utf_7") |
| 282 |
codec_register_alias("65001", "utf_8") |
| 283 |
codec_register_alias("cp65000", "utf_7") |
| 284 |
codec_register_alias("cp65001", "utf_8") |
| 285 |
codecs.register(lambda alias: _codecs.get(alias)) |
| 286 |
|
| 287 |
|
| 288 |
if __name__ == "__main__": |
| 289 |
test = "test \u00e4\u00f6\u00fc\ufffe test" |
| 290 |
try: |
| 291 |
print(test) |
| 292 |
except (OSError, LookupError, UnicodeError) as exception: |
| 293 |
print(f"could not print {test!r}:", exception) |
| 294 |
print("wrapping stdout/stderr via encodestdio()") |
| 295 |
encodestdio() |
| 296 |
print(test) |
| 297 |
print("exiting normally") |