Skip to content

Commit

Permalink
force utf8 mode when sys.stdout.encoding is ASCII
Browse files Browse the repository at this point in the history
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...

#136
  • Loading branch information
oconnor663 committed Nov 16, 2015
1 parent 34d685d commit a8072aa
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions peru/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,22 @@ def docopt_parse_args(argv):
'CommandParams', ['args', 'runtime', 'scope', 'imports'])


def force_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)


def main(*, argv=None, env=None, nocatch=False):
force_utf8_in_ascii_mode_hack()

if argv is None:
argv = sys.argv[1:]
if env is None:
Expand Down

0 comments on commit a8072aa

Please sign in to comment.