-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole_utils.py
More file actions
48 lines (39 loc) · 1.33 KB
/
console_utils.py
File metadata and controls
48 lines (39 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import sys
import unicodedata
def configure_stdio():
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)
if stream is None or not hasattr(stream, "reconfigure"):
continue
try:
stream.reconfigure(encoding="utf-8", errors="backslashreplace")
except Exception:
pass
def _normalize_console_text(value):
text = unicodedata.normalize("NFKC", str(value or ""))
text = text.replace("\r\n", "\n").replace("\r", "\n")
return text.replace("\x00", "")
def safe_print(*values, sep=" ", end="\n", file=None, flush=False):
stream = file or sys.stdout
text = sep.join(_normalize_console_text(value) for value in values)
try:
print(text, end=end, file=stream, flush=flush)
return
except UnicodeEncodeError:
pass
except Exception:
return
encoding = getattr(stream, "encoding", None) or "utf-8"
payload = (text + end).encode(encoding, errors="backslashreplace")
buffer = getattr(stream, "buffer", None)
try:
if buffer is not None:
buffer.write(payload)
if flush:
buffer.flush()
return
stream.write(payload.decode(encoding, errors="ignore"))
if flush:
stream.flush()
except Exception:
pass