Skip to content

Instantly share code, notes, and snippets.

@techtonik
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techtonik/574401cebf5e17c33f5b to your computer and use it in GitHub Desktop.
Save techtonik/574401cebf5e17c33f5b to your computer and use it in GitHub Desktop.
Python 2.8 Rationale
# Solve problem of Python 2.7 defaults
# 1. switch internal Python 2 encoging from internal ASCII to Unicode
# (this fixes interoperability of Jinja2 with tools that use binary
# utf-8 for passing strings instead of Unicode, e.g. Roundup)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 2. do not fail on printing stuff to stdout/stderr, but escape it
# (removes negative emotions trying to debug binary strings with print)
import codecs
if sys.stdout.isatty():
# ^ otherwise sys.stdout.encoding will not be set
sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout, 'backslashreplace')
else:
# piped or redirected
if sys.platform == "win32":
# reopen stdout as binary stream to avoid corruption of \n to \r\n
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
if sys.stderr.isatty():
sys.stderr = codecs.getwriter(sys.stderr.encoding)(sys.stdout, 'backslashreplace')
else:
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment