Skip to content

Commit 549c1d0

Browse files
committed
First try output as str, then move to bytes, then ascii str
1 parent 37332c3 commit 549c1d0

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/mbed_os_tools/test/mbed_test_api.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def run_htrun(cmd, verbose):
125125
htrun_failure_line = re.compile('\[RXD\] (:\d+::FAIL: .*)')
126126

127127
for line in iter(p.stdout.readline, b''):
128-
decoded_line = line.decode('utf-8', 'ignore')
128+
decoded_line = line.decode("utf-8", "replace")
129129
htrun_output += decoded_line
130130
# When dumping output to file both \r and \n will be a new line
131131
# To avoid this "extra new-line" we only use \n at the end
@@ -135,7 +135,20 @@ def run_htrun(cmd, verbose):
135135
gt_logger.gt_log_err(test_error.group(1))
136136

137137
if verbose:
138-
sys.stdout.write(decoded_line.rstrip() + '\n')
138+
output = decoded_line.rstrip() + '\n'
139+
try:
140+
# Try to output decoded unicode. Should be fine in most Python 3
141+
# environments.
142+
sys.stdout.write(output)
143+
except UnicodeEncodeError:
144+
try:
145+
# Try to encode to unicode bytes and let the terminal handle
146+
# the decoding. Some Python 2 and OS combinations handle this
147+
# gracefully.
148+
sys.stdout.write(output.encode("utf-8"))
149+
except TypeError:
150+
# Fallback to printing just ascii characters
151+
sys.stdout.write(output.encode("ascii", "replace").decode("ascii"))
139152
sys.stdout.flush()
140153

141154
# Check if process was terminated by signal

0 commit comments

Comments
 (0)