带有编解码器的pycharm utf-8编码来自系统stdout和stderr

时间:2017-06-06 20:58:55

标签: python python-3.x encoding utf-8

请大家好,我在pycharm社区版2016.3.2中的一个项目上使用python 3.6.0。每当我使用编解码器对输入流进行编码时,我的程序就会发生这个奇怪的错误:

import codecs
import sys

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

print("something")

问题是我的程序总是以退出代码1退出,这是控制台输出:

Traceback (most recent call last):
  File "C:/Users/jhonsong/Desktop/restfulAPI/findARestaurant.py", line 9, in <module>
    print("something")
  File "C:\Python36-32\lib\codecs.py", line 377, in write
    self.stream.write(data)
TypeError: write() argument must be str, not bytes

Process finished with exit code 1

但我的输入是一个字符串,为什么codecs.write认为我给它输入字节?

1 个答案:

答案 0 :(得分:1)

在Python 3中,sys.stdout是一个Unicode流。 codecs.getwriter('utf8')需要一个字节流。 sys.stdout.buffer是原始字节流,因此请使用:

sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer)

但是对于Python 3.6来说这似乎有些过分,print应该可以正常工作。通常,如果您需要强制编码,比如将Python脚本的输出捕获到特定编码的文件中,则以下脚本(Windows)将起作用。环境变量指示输出编码并覆盖终端默认值。

set PYTHONIOENCODING=utf8
python some_script.py > output.txt

由于您要提交到某个网站,该网站应负责以能够正确捕获结果的方式运行您的脚本。