

_stdout.write(s.encode(self.encoding, 'backslashreplace')) Getattr(org_stdout, 'encoding', None) or 'utf-8' Org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)

When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.ĭef _init_(self, encoding=None, org_stdout=None): At last by replacing sys.stdout & sys.stderr by a translating file-like object. When is None for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs: The best solution I know for solving the encode problem of print'ing unicode strings and beyond-ascii str's (e.g.

sys.stdin/stdout streams, sys.excepthook, etc. reload often changes things in sys which have been put in place depending on the environment - e.g. When I use virtualenvwrapper the file I edit is ~/.virtualenvs/venv-name/lib/python2.7/sitecustomize.py.Īnd when I use with python notebooks and conda, it is ~/anaconda2/lib/python2.7/sitecustomize.pyįirst: reload(sys) and setting some random default encoding just regarding the need of an output terminal stream is bad practice. So the solution is to append to file /usr/lib/python2.7/sitecustomize.py the code: import sys After evaluating that module, the setdefaultencoding function is removed from sys. I guess there would be solution to it, but still I think using the hack should not be the correct option.Īfter trying many options, the one that worked for me was using the same code in the sitecustomize.py, where that piece of code is meant to be. In my case, it come with a side-effect: I'm using ipython notebooks, and once I run the code the ´print´ function no longer works.

It is discouraged to use it (check this or this) Regarding python2 (and python2 only), some of the former answers rely on using the following hack: import sys
