In some environments (particularly Docker), Python tends to start up with the locale set to ASCII. That means trying to print unicode characters raises an exception, like in our fancy display. Rather than requiring the user to explicitly set PYTHONIOENCODING=utf8, we rewrap stdout and stderr in UTF8 file objects.
I’m a little worried that this will break something down the line…
好几年前遇到的一个错误,最近再整理浏览器书签的时候刚好看到,就整理到自己的博客。
解决方法
1 2 3 4 5 6 7 8
defforce_utf8_in_ascii_mode_hack(): '''In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru inside of Docker. This is a hack to force emitting UTF8 in that case. Hopefully it doesn't break anything important.''' if sys.stdout.encoding == 'ANSI_X3.4-1968': sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1) sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)