This question already has answers here:
Setting the correct encoding when piping stdout in Python
(10个答案)
7年前关闭。
我在Python中遇到有关Unicode的问题。我可以在常规终端中很好地打印输出,但是如果我将
为什么是这样?我该如何解决?
(10个答案)
7年前关闭。
我在Python中遇到有关Unicode的问题。我可以在常规终端中很好地打印输出,但是如果我将
stdout
重定向到其他地方(或使用subprocess
模块捕获它),则会得到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)
为什么是这样?我该如何解决?
最佳答案
没有通向终端的管道没有编码,因此您需要检查 sys.stdout.isatty()
并在需要时进行编码。
关于python - 重定向标准输出时出现UnicodeEncodeError ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2224130/