I'm having a problem regarding Unicode in Python. I can print the output fine in a regular terminal, but if I redirect stdout
elsewhere (or capture it with the subprocess
module), I get a UnicodeEncodeError
:
$ cat example.py print u'Example: \u00F1' $ python example.py Example: ñ $ python example.py > /dev/null Traceback (most recent call last): File "example.py", line 1, in <module> print u'Example: \u00F1' UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 9: ordinal not in range(128)
Why is this? How can I fix it?
Pipes that don't lead to the terminal don't have an encoding, therefore you'll need to check sys.stdout.isatty()
and encode if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With