为什么这个程序(开放编码utf8 utf8sig)在某些上下文中失败,而不是在其他上下文中失败

2024-05-19 10:09:46 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么,有了这个程序:

import sys

print("sys.getdefaultencoding()='%s'" % (sys.getdefaultencoding(), ))

with open("example.txt", "w", encoding="utf-8-sig", errors="replace") as f:
    f.write("test;Ilość sztuk\n")

with open("example.txt", "r", errors="strict") as rf:
    lr = rf.readline()
    print("lr=", lr)

在某些上下文中运行OK,在其他上下文中运行失败。你知道吗

示例OK:

$ python3 ./example.py 
sys.getdefaultencoding()='utf-8'
lr= test;Ilość sztuk

注:

$ python3 --version
Python 3.6.8

示例KO:

sys.getdefaultencoding()='utf-8'
Traceback (most recent call last):
  File "./example.py", line 9, in <module>
    lr = rf.readline()
  File "/.../python/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
$

注:

$ python3 --version
Python 3.6.8

上下文是:ubuntu19.04,ubuntu18.04,debian9,in-chroot,outside-chroot,LANG是“en”_美国.UTF-8“或”fr_法国UTF-8“,不影响成功或失败

在所有情况下,Python都是使用相同的选项手动安装的。你知道吗

如果你需要某个环境变量的值,我可以给你。你知道吗

我希望在所有情况下都有完全相同的处决。你知道吗


Tags: inpyexamplewithsysasciiopenpython3
1条回答
网友
1楼 · 发布于 2024-05-19 10:09:46

在Python3中,有不同的编码默认值。 找到的^{}告诉您方法str.encode()bytes.decode()的默认值。 据我所知,不管您使用什么Python构建或实现,它总是UTF-8。你知道吗

但是,如果在对open()的调用中省略encoding=...参数,则使用^{};对于sys.stdinsys.stdoutprint()!),sys.stderr。 此默认值的值取决于启动Python解释器的环境。 如何确定该值的细节在不同平台之间有所不同,但通常可以通过设置PYTHONIOENCODINGenv变量来实现所需的行为。 从python3.7开始,可以使用-X utf8启动Python以启用UTF-8模式。你知道吗

相关问题 更多 >

    热门问题