Before encountering this exception unicodeencodeerror: ' ASCII ' codec can ' t encode characters ..., is resolved in this way: sys.setdefaultencoding (' Utf-8 ')
See the following article today, explaining the drawbacks of this approach:
Http://blog.ernest.me/post/python-setdefaultencoding-unicode-bytes
However, this article only considers the solution without using a third-party library, and if there is print in the third-party library, there is no way to add encode to all of the third-party print.
In addition, this article said that the change code is the hidden danger of utf8, in fact, because there is no use of Unicode string or two strings mixed only, if the project can only use U ' Unicode string ', the above hidden danger can be basically avoided. The biggest risk in the final analysis is that third-party libraries are not controllable, print encodings and Unicode strings are not controllable, so setdefaultencoding cannot be used.
This time I was using Java to launch Python, print Chinese, will report the exception of ASCII, I found that in this case sys.stdout.encoding is actually none, and in Ubuntu Normal command line this variable is UTF-8.
So how do you change sys.stdout.encoding? (Direct modification will be error typeerror:readonly attribute)
So I finally found http://www.macfreek.nl/memory/Encoding_of_Python_stdout.
Python2 Modification Method (Python3 slightly different, also written in the original)
1 ifSys.stdout.encoding! ='UTF-8':2Sys.stdout = Codecs.getwriter ('Utf-8') (Sys.stdout,'Strict')3 ifSys.stderr.encoding! ='UTF-8':4Sys.stderr = Codecs.getwriter ('Utf-8') (Sys.stderr,'Strict')
This solves the problem of ASCII encoding when the output is Chinese, and does not have to reset the SYS's default encoding.
The solution of Python Print report ASCII coding anomaly