我在同一个项目中使用 Windows 和 Linux 机器。在 Windows 上,stdin 的默认编码是 cp1252,在 Linux 上则是 utf-8。
我希望把所有内容都改成 utf-8。这可行吗?我该如何做?
这个问题涉及 Python 2;有关 Python 3,请参见Python 3:如何指定 stdin 编码。
我在同一个项目中使用 Windows 和 Linux 机器。在 Windows 上,stdin 的默认编码是 cp1252,在 Linux 上则是 utf-8。
我希望把所有内容都改成 utf-8。这可行吗?我该如何做?
这个问题涉及 Python 2;有关 Python 3,请参见Python 3:如何指定 stdin 编码。
你可以通过不依赖于打印东西时的隐式编码来实现这一点。无论如何,不依赖隐式编码都是一个好主意--隐式编码只在将输出打印到标准输出且标准输出连接到终端时使用。
一个更好的方法是在任何地方都使用unicode
,并且在任何地方都使用codecs.open
或者codecs.getwriter
。你可以将sys.stdout
包装在一个对象中,该对象会自动将你的unicode字符串转换为UTF-8格式,例如:
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
只有当你在所有地方都使用Unicode时,才能使其起作用。因此,请在任何地方都使用Unicode。真的,任何地方。
这是一个旧问题,但仅供参考。
要从标准输入读取 UTF-8
,请使用:
UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin)
# Then, e.g.:
for _ in sys.stdin:
print _.strip()
要将UTF-8
写入stdout
,请使用:
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
# Then, e.g.:
print 'Anything'
codecs.getreader('utf-8')(sys.stdin)
(相当于本帖子)不起作用。请使用 codecs.getreader('utf-8')(sys.stdin.buffer)
和 codecs.getwriter('utf8')(sys.stdout.buffer)
。 - EponymousPython会自动检测stdin的编码。当自动检测无法正常工作时,我发现最简单的指定编码的方法是使用 PYTHONIOENCODING 环境变量,例如以下示例:
pipeline | PYTHONIOENCODING="UTF-8" /path/to/your-script.py
如需了解有关不同平台上编码检测和此变量的更多信息,请查看sys.stdin文档。
from sys import version_info
if version_info.major == 2: # for python2
import codecs
# for stdin
UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin)
# for stdout
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
elif version_info.major == 3: # for python3
import codecs
# for stdin
UTF8Reader = codecs.getreader('utf8')
sys.stdin = UTF8Reader(sys.stdin.buffer)
# for stdout
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout.buffer)
codecs.getreader('utf-8')(sys.stdin)
。 - Thomas Wouterscodecs.getreader('utf-8')(sys.stdin)
不起作用。请改用codecs.getreader('utf-8')(sys.stdin.buffer)
和codecs.getwriter('utf8')(sys.stdout.buffer)
。 - Eponymous