I am trying to handle the different encodings in a Python script the more user-friendly and auto-magic way possible (there are APIs for utf8). It is a cross-platform console script.
For printing to stdout I use sys.stdout.encoding and it seems to do the right thing almost always when printing to the console. However when stdout is piped it becomes None.
So in that case I assume I am piping to a file and use locale.getpreferredencoding() but:

I am not sure this is the right encoding for printing to a file, but it works quite cross-platform.
That doesn't work when piping to a program |. I don't know how to detect that this is the case neither if there is a standard or an expected behavior for encoding in that case.
If it is None, simply output your data as utf-8, and document it.  If it happens that there are use cases for other encodings, make that an option through the command line or other means.
What should I do when sys.stdout.encoding is None?