Assume for a moment that one cannot use print
(and thus enjoy the benefit of automatic encoding detection). So that leaves us with sys.stdout
. Howe
Best idea is to check if you are directly connected to a terminal. If you are, use the terminal's encoding. Otherwise, use system preferred encoding.
if sys.stdout.isatty():
default_encoding = sys.stdout.encoding
else:
default_encoding = locale.getpreferredencoding()
It's also very important to always allow the user specify whichever encoding she wants. Usually I make it a command-line option (like -e ENCODING
), and parse it with the optparse
module.
Another good thing is to not overwrite sys.stdout
with an automatic encoder. Create your encoder and use it, but leave sys.stdout
alone. You could import 3rd party libraries that write encoded bytestrings directly to sys.stdout
.