/
fixunicode.py
49 lines (38 loc) · 1.6 KB
/
fixunicode.py
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
49
"""
Module which forces stdout/stderr into a mode which allows unicode output.
"""
import sys
try:
sys.stdout.write("\u2603")
sys.stdout.write("\b")
except UnicodeEncodeError as e:
pass
try:
sys.stderr.write("\u2603")
sys.stderr.write("\b")
except UnicodeEncodeError as e:
pass
if sys.stdout.encoding != "UTF-8" or sys.stderr.encoding != "UTF-8":
from ctypes import pythonapi, py_object, c_char_p
PyFile_SetEncoding = pythonapi.PyFile_SetEncoding
PyFile_SetEncoding.argtypes = (py_object, c_char_p)
if sys.stdout.encoding != "UTF-8":
if not PyFile_SetEncoding(sys.stdout, "UTF-8"):
raise SystemError("Unable to force stdout to UTF-8, PyFile_SetEncoding failed.")
if sys.stdout.encoding != "UTF-8":
raise SystemError("Unable to force stdout to UTF-8, encoding still %s." % sys.stdout.encoding)
if sys.stderr.encoding != "UTF-8":
if not PyFile_SetEncoding(sys.stderr, "UTF-8"):
raise SystemError("Unable to force stderr to UTF-8, PyFile_SetEncoding failed.")
if sys.stderr.encoding != "UTF-8":
raise SystemError("Unable to force stderr to UTF-8, encoding still %s." % sys.stderr.encoding)
try:
sys.stdout.write("\u2603")
sys.stdout.write("\b")
except UnicodeEncodeError as e:
raise SystemError("Unable to write unicode on stdout (encoding %s).\n%s" % (sys.stdout.encoding, e))
try:
sys.stderr.write("\u2603")
sys.stderr.write("\b")
except UnicodeEncodeError as e:
raise SystemError("Unable to write unicode on stderr (encoding %s).\n%s" % (sys.stderr.encoding, e))