Encoding Output in Python 3: Setting sys.stdout's Encoding
In Python 2, the default output encoding could be effortlessly altered by wrapping sys.stdout within a codec writer. However, in Python 3, this technique is rendered obsolete due to the incongruity between the str type expected by sys.stdout.write() and the bytes produced by encoding.
Resolution in Python 3
Beginning with Python 3.7, the reconfigure() method provides a direct solution for modifying the encoding of standard streams, including sys.stdout:
sys.stdout.reconfigure(encoding='utf-8')
This approach effectively changes the encoding to UTF-8. Moreover, you can refine the handling of encoding errors by specifying an errors parameter:
sys.stdout.reconfigure(encoding='utf-8', errors='ignore')
This customization ensures that any encoding errors are silently disregarded, enabling seamless output operations. By utilizing the reconfigure() method, Python 3 programmers can effortlessly modify the encoding of sys.stdout, empowering them to produce consistent and reliable text output across various systems and applications.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3