Skip to content

Commit 1650f24

Browse files
committed
Add pythainlp.tools.safe_print
Handle Unicode print on console
1 parent 3377ec0 commit 1650f24

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

pythainlp/tools/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
"get_full_data_path",
77
"get_pythainlp_data_path",
88
"get_pythainlp_path",
9+
"safe_print",
910
"warn_deprecation",
1011
]
1112

12-
from pythainlp.tools.core import warn_deprecation
13+
from pythainlp.tools.core import safe_print, warn_deprecation
1314
from pythainlp.tools.path import (
1415
PYTHAINLP_DEFAULT_DATA_DIR,
1516
get_full_data_path,

pythainlp/tools/core.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
Generic support functions for PyThaiNLP.
66
"""
77

8+
import sys
89
import warnings
910

1011

@@ -13,8 +14,7 @@ def warn_deprecation(
1314
replacing_func: str = "",
1415
version: str = "",
1516
):
16-
"""
17-
Warn about the deprecation of a function.
17+
"""Warn about the deprecation of a function.
1818
1919
:param str deprecated_func: Name of the deprecated function.
2020
:param str replacing_func: Name of the function to use instead (optional).
@@ -28,3 +28,19 @@ def warn_deprecation(
2828
if replacing_func:
2929
message += f" Please use '{replacing_func}' instead."
3030
warnings.warn(message, DeprecationWarning, stacklevel=2)
31+
32+
33+
def safe_print(text: str):
34+
"""Print text to console, handling UnicodeEncodeError.
35+
36+
:param text: Text to print.
37+
:type text: str
38+
"""
39+
try:
40+
print(text)
41+
except UnicodeEncodeError:
42+
print(
43+
text.encode(sys.stdout.encoding, errors="replace").decode(
44+
sys.stdout.encoding
45+
)
46+
)

0 commit comments

Comments
 (0)