Debian Codegraph @

DisplayCAL/safe_print.py

raw
1 """Safely print to streams, avoiding Unicode errors.
2
3 It ensures compatibility with various encodings and allows customization of
4 padding, separators, and output formatting. A global `safe_print` instance is
5 also provided for convenience.
6 """
7
8 # Standard Library Imports
9 from __future__ import annotations
10
11 import os
12 import sys
13 from typing import BinaryIO, Callable
14
15 # Local Imports
16 from DisplayCAL.encoding import get_encodings
17
18 ORIGINAL_CODEPAGE = None
19 ENC, FS_ENC = get_encodings()
20 _CONWIDTH = None
21
22
23 def _get_console_width() -> int:
24 """Get the width of the console in characters.
25
26 Returns:
27 int: The width of the console.
28 """
29 global _CONWIDTH
30 if _CONWIDTH is None:
31 _CONWIDTH = 80
32 try:
33 if sys.platform == "win32":
34 import struct
35 from ctypes import create_string_buffer, windll
36
37 # Use stderr handle so that pipes don't affect the reported size
38 stderr_handle = windll.kernel32.GetStdHandle(-12)
39 buf = create_string_buffer(22)
40 consinfo = windll.kernel32.GetConsoleScreenBufferInfo(
41 stderr_handle, buf
42 )
43 if consinfo:
44 _CONWIDTH = struct.unpack("hhhhHhhhhhh", buf.raw)[0]
45 else:
46 _CONWIDTH = int(os.getenv("COLUMNS"))
47 except Exception:
48 pass
49 return _CONWIDTH
50
51
52 class SafePrinter:
53 r"""A class for safely printing to a stream, avoiding Unicode errors.
54
55 Write safely, avoiding any UnicodeDe-/EncodingErrors on strings and
56 converting all other objects to safe string representations.
57
58 sprint = SafePrinter(pad=False, padchar=' ', sep=' ', end=r'\n',
59 file=sys.stdout, fn=None)
60 sprint(value, ..., pad=False, padchar=' ', sep=' ', end=r'\n',
61 file=sys.stdout, fn=None)
62
63 Writes the values to a stream (default sys.stdout), honoring its
64 encoding and replacing characters not present in the encoding with
65 question marks silently.
66
67 Args:
68 pad (bool | int, optional): Pad the lines to n chars, or
69 os.getenv('COLUMNS') if True.
70 padchar (str, optional): Character to use for padding, default a space.
71 sep (str, optional): String inserted between values, default a space.
72 end (str, optional): String appended after the last value, default a
73 newline.
74 file (BinaryIO, optional): A file-like object (stream); defaults to
75 the sys.stdout.
76 fn (Callable, optional): A function to execute instead of printing.
77 """
78
79 def __init__(
80 self,
81 pad: bool | int = False,
82 padchar: str = " ",
83 sep: str = " ",
84 end: str = "\n",
85 file_: BinaryIO = sys.stdout,
86 fn: None | Callable = None,
87 encoding: None | str = None,
88 ) -> None:
89 self.pad = pad
90 self.padchar = padchar
91 self.sep = sep
92 self.end = end
93 self.file = file_
94 self.fn = fn
95 self.encoding = encoding or "utf-8"
96
97 def __call__(self, *args, **kwargs) -> None:
98 """Call the instance to write the given arguments to the stream."""
99 # TODO: Why calling the instance writes it, this is not a good practice.
100 self.write(*args, **kwargs)
101
102 def flush(self) -> None:
103 """Flush the output stream."""
104 self.file and self.file.flush()
105
106 def write(self, *args, **kwargs) -> None:
107 """Write the given arguments to the stream, formatted and encoded."""
108 pad = kwargs.get("pad", self.pad)
109 padchar = kwargs.get("padchar", self.padchar)
110 sep = kwargs.get("sep", self.sep)
111 end = kwargs.get("end", self.end)
112 file_ = kwargs.get("file_", self.file)
113 fn = kwargs.get("fn", self.fn)
114 encoding = self.encoding
115
116 # convert everything to bytes
117 if isinstance(padchar, str):
118 padchar = padchar.encode(self.encoding)
119 if isinstance(sep, str):
120 sep = sep.encode(self.encoding)
121 if isinstance(end, str):
122 end = end.encode(self.encoding)
123
124 strargs = []
125 for arg in args:
126 if not isinstance(arg, bytes):
127 arg = bytes(arg, encoding, "asciize")
128 strargs.append(arg)
129 line = sep.join(strargs).rstrip(end)
130 if pad is not False:
131 width = _get_console_width() if pad is True else int(pad)
132 line = line.ljust(width, padchar)
133 if fn:
134 fn(line)
135 else:
136 try:
137 if "b" not in file_.mode:
138 line = line.decode(self.encoding)
139 if end:
140 end = end.decode(self.encoding)
141 file_.write(line)
142 if end:
143 file_.write(end)
144 except OSError:
145 pass
146
147
148 safe_print = SafePrinter()
149
150
151 if __name__ == "__main__":
152 for arg in sys.argv[1:]:
153 print(arg)