为什么,使用这个程序:
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:
$ 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上下文是;Ubuntu 19.04,Ubuntu 18.04,Debian 9,in chroot,on chroot,LANG是"en_US.UTF-8“或"fr_FR.UTF-8",对成功或失败没有影响
在所有情况下,Python都是使用相同选项手动安装。
如果你需要某个环境变量的值,我可以给你。
我搜索在所有情况下都有完全相同的执行。
发布于 2019-09-14 04:08:29
在Python 3中,有不同的编码默认值。您找到的sys.getdefaultencoding()告诉您str.encode()和bytes.decode()方法的默认值。据我所知,无论您使用什么版本或实现的Python,它都是UTF-8。
但是,如果在调用open()时省略了encoding=...参数,那么将使用locale.getdpreferredencoding();对于sys.stdin,也可以使用sys.stdout (print()!)和sys.stderr。此默认值取决于启动Python解释器的环境。关于如何确定此值的详细信息因平台而异,但通常您可以通过设置PYTHONIOENCODING环境变量来实现所需的行为。从Python3.7开始,您可以通过-X utf8启动Python来启用UTF-8模式。
https://stackoverflow.com/questions/57919011
复制相似问题