使用 Python 3 中的编码打印到标准输出

问题描述 投票:0回答:4

我有一个 Python 3 程序,可以从 Windows-1252 编码文件中读取一些字符串:

with open(file, 'r', encoding="cp1252") as file_with_strings:
    # save some strings

我稍后想将其写入标准输出。我尝试过:

print(some_string)
# => UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 180: ordinal not in range(128)

print(some_string.decode("utf-8"))
# => AttributeError: 'str' object has no attribute 'decode'

sys.stdout.buffer.write(some_str)
# => TypeError: 'str' does not support the buffer interface

print(some_string.encode("cp1252").decode("utf-8"))
# => UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 180: invalid continuation byte

print(some_string.encode("cp1252"))
# => has the unfortunate result of printing b'<my string>' instead of just the string

我在这里摸不着头脑。我想打印从文件中获得的字符串,就像它在 cp1252 中出现的那样。 (在我的终端中,当我执行

more $file
时,这些字符显示为问号,因此我的终端可能是 ascii。)

希望得到一些澄清!谢谢!

python python-3.x character-encoding
4个回答
8
投票

从 Python 3.7 开始,您可以使用

sys.stdout
 方法更改写入 
reconfigure
的所有文本的编码:

import sys

sys.stdout.reconfigure(encoding="cp1252")

如果您需要更改程序所有输出的编码,这可能会很有帮助。


2
投票

对于任何有同样问题的人,我最终做了:

to_print = (some_string + "\n").encode("cp1252")
sys.stdout.buffer.write(to_print)
sys.stdout.flush() # I write a ton of these strings, and segfaulted without flushing

1
投票

当你用cp1252编码时,你必须用同样的解码。

例如:

import sys
txt = ("hi hello\n").encode("cp1252")
#print((txt).decode("cp1252"))
sys.stdout.buffer.write(txt)
sys.stdout.flush()

这将打印“嗨你好 “(在 cp1252 中编码)解码后。


0
投票

您要么正在通过管道传输脚本,要么您的区域设置已损坏。您应该修复您的环境,而不是将脚本固定到您的环境中,因为这将使您的脚本非常脆弱。

如果您使用管道,Python 假定输出应为“ASCII”,并将 stdout 的编码设置为“ASCII”。

在正常情况下,Python 使用

locale
来确定应用于 stdout 的编码。如果您的语言环境损坏(未安装或损坏),Python 将默认为“ASCII”。区域设置“C”也会为您提供“ASCII”编码。

输入

locale
检查您的区域设置,并确保不会返回任何错误。例如

$ locale
LANG="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_CTYPE="en_GB.UTF-8"
LC_MESSAGES="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_ALL=

如果所有其他方法都失败或者您正在使用管道,您可以通过设置

PYTHONIOENCODING
环境变量来覆盖 Python 的区域设置检测。例如

$ PYTHONIOENCODING=utf-8 ./my_python.sh

请记住,您的 shell 有一个语言环境,您的终端有一个编码 - 它们都需要正确设置

© www.soinside.com 2019 - 2024. All rights reserved.