Categories
Python Answers

How to set the correct encoding when piping stdout in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *