The solution of Python Print report ASCII coding anomaly

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.