python / python/cpython

Windows code page codec cannot encode with code pages that require dwFlags=0

未关闭
#155,016 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

3.13 3.14 3.15 3.16 OS-windows topic-unicode type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug report

On Windows, codecs.code_page_encode() fails with OSError: [WinError 87] The parameter is incorrect for every code page that WideCharToMultiByte() requires to be called with dwFlags = 0 and lpUsedDefaultChar = NULL: 50220, 50221, 50222, 50225, 50227, 50229, 52936 (HZ-GB2312), 54936 (GB18030), 57002-57011 (ISCII), 65000 and 42. Decoding these code pages works.

>>> import codecs
>>> codecs.code_page_decode(50220, b'\x1b$B$"\x1b(B')
('あ', 8)
>>> codecs.code_page_encode(50220, 'あ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect

encode_code_page_flags() returns WC_NO_BEST_FIT_CHARS, and encode_code_page_strict() passes a non-NULL lpUsedDefaultChar, for every code page except CP_UTF8 and CP_UTF7. decode_code_page_strict() retries with flags = 0 when MultiByteToWideChar() fails with ERROR_INVALID_FLAGS; the encoder has no such fallback. With dwFlags = 0 and lpUsedDefaultChar = NULL the conversion works:

>>> import ctypes
>>> buf = ctypes.create_string_buffer(64)
>>> n = ctypes.windll.kernel32.WideCharToMultiByte(50220, 0, 'あ', 1, buf, 64, None, None)
>>> buf.raw[:n]
b'\x1b$B$"\x1b(B'

Note that usedDefaultChar is how the encoder detects unencodable characters, so dropping it needs a replacement (for example decoding the result back and comparing).

cp51932, cp51936 and cp51950 fail in both directions; those code pages are not supported by MultiByteToWideChar()/WideCharToMultiByte() at all.

Linked PRs
  • gh-155018

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 codecs.code_page_encode() 以及 encode_code_page_flags() 和 encode_code_page_strict() 这两个辅助函数开始,然后将它们的行为与 decode_code_page_strict() 进行比较。复现 code page 50220 的失败,并验证列出的 Windows code page 能够成功编码,同时不可编码字符的检测仍然得到覆盖。关联的 PR gh-155018 表明相关工作已经在进行中。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
30/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。