Sometimes, we want to set the correct encoding when piping stdout in Python.
In this article, we’ll look at how to set the correct encoding when piping stdout in Python.
How to set the correct encoding when piping stdout in Python?
To set the correct encoding when piping stdout in Python, we can set sys.stdout
to the right encoding.
For instance, we write
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
to call codecs.getwriter
with 'utf8'
to set the encoding to utf8.
And then we call the returned function with sys.stdout
to set the stdout’s encoding to utf8.
Finally, we assign the returned object to sys.stdout
to set the encoding.
Conclusion
To set the correct encoding when piping stdout in Python, we can set sys.stdout
to the right encoding.