目录

一个poetry编码问题的定位

一个poetry编码问题的定位

问题描述

在使用PyCharm打开某个Poetry项目时,选择Create a poetry environment using pyproject.toml,在环境构建过程中报错:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Installing dependencies from lock file

Package operations: 25 installs, 0 updates, 0 removals


  UnicodeEncodeError

  'gbk' codec can't encode character '\u2022' in position 2: illegal multibyte sequence

  at ~\.poetry\lib\poetry\_vendor\py3.10\clikit\io\output_stream\stream_output_stream.py:24 in write
       20         """
       21│         if self.is_closed():
       22│             raise io.UnsupportedOperation("Cannot write to a closed input.")
       23│ 
    →  24│         self._stream.write(string)
       25│         self._stream.flush()
       26│ 
       27│     def flush(self):  # type: () -> None
       28│         

环境信息: Windows10+PyCharm+Python3.10+Poetry1.1.14

问题定位

考虑存在文件读取编码问题

无效配置1: PyCharm FileEncodings

由于使用Pycharm,设置Settings-Editor-File Encodings,设置:

  • Global Encoding: UTF-8

  • Project Encoding: UTF-8

重新创建Poetry环境,仍然报错

无效配置2:PyCharm Custom VM Options

考虑设置PyCharm JVM环境编码,设置Help-Edit Custom VM Options... 增加参数

1
-Dfile.encoding=utf-8

重启PyCharm,重新创建Poetry环境,仍然报错

有效配置:设置PYTHONUTF8

查看报错日志,Poetry创建环境时报错~\.poetry\lib\poetry\_vendor\py3.10\clikit\io\output_stream\stream_output_stream.py:24, 考虑可能Poetry本身问题,读取文件时使用的是操作系统默认编码

而在Windows中默认编码locale.getpreferredencoding()是GBK编码,所以存在读取错误的问题

问题解决:

在Windows环境变量中增加 PYTHONUTF8=1, 重启PyCharm,问题解决

PYTHONUTF8参数解释

PYTHONUTF8是从Python3.7版本引入的参数,表示是否启用Python UTF-8 Mode, 在该模式下,Python会忽略locale encoding,强制使用UTF-8编码。

中文的Windows系统,默认本地编码是GBK,可以通过locale.getpreferedencoding()获取,Python使用本地编码作为默认的文本文件编码,这就导致文件中存在UTF-8编码时使用默认的编码会报错。

而设置PYTHONUTF8参数为1后,Python启用Python UTF-8 Mode, 强制使用UTF-8编码,问题得以解决,归根结底个人认为这仍是Poetry的问题导致的,正常在读取文件系统上的python文件时设置一下编码就不应该存在这种问题