Home > Article > Backend Development > How to Set `sys.stdout` Encoding in Python 3?
Python 3: Altering sys.stdout Encoding
In Python 2, setting the default output encoding was straightforward through sys.stdout = codecs.getwriter("utf-8")(sys.stdout). However, this technique proves problematic in Python 3, as sys.stdout.write(), expecting a string, conflicts with the byte-encoded output from the codec.
To effectively set the sys.stdout encoding in Python 3, employ the reconfigure() method introduced in Python 3.7. This method allows you to specify the desired encoding:
sys.stdout.reconfigure(encoding='utf-8')
Additionally, you can control error handling behavior using the errors parameter:
sys.stdout.reconfigure(encoding='utf-8', errors='replace') # Error handling option
The above is the detailed content of How to Set `sys.stdout` Encoding in Python 3?. For more information, please follow other related articles on the PHP Chinese website!