When you use Python with sys.stdout you might run into a problem where sys.stdout.encoding suddenly becomes None. This happens due to the fact that upon using a pipe or redirection, at least under Unix, it falls back to not knowing anything about the target. In order to work around this you can add a fallback to use locale.getpreferredencoding(). So if you use encode() on a string you can do something like:
from locale import getpreferredencoding text = u"Something special" print text.encode(sys.stdout.encoding or getpreferredencoding() or 'ascii', 'replace')
This is how we currently use it within Babel as well for printing the locale list.