【问题标题】:Python3.7 & Windows : incorrect unicode characters in docstrings in interactive modePython3.7 & Windows:交互模式下文档字符串中的 unicode 字符不正确
【发布时间】:2021-01-16 09:29:43
【问题描述】:

将以下程序另存为test.py:

def f():
    """àâùç"""
    return
print("àâùç")

并在 Windows cmd-window 中以交互模式执行它:

python -i test.py

printed 的文字是正确的,但是当我打电话给 help(f) 时,我得到了炒鸡蛋:

P:\>python -i test.py
àâùç
>>> help(f)
Help on function f in module __main__:

f()
    ÓÔ¨þ

将代码页更改为 65001 会显示经典的神秘卡片:

P:\>python -i test.py
àâùç
>>> help(f)
Help on function f in module __main__:

f()
    ����

有没有(简单的)解决方法?

【问题讨论】:

  • 尝试chcp 1252,因为help() 代表ACP 代码页(reg query "HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage" -v ACP)。
  • 似乎是 print() 正常工作并且 help() 编码为 ANSI(美国和西欧 Windows 上为 1252)的错误。 Windows 终端的默认编码是西欧 Windows 上的“OEM ANSI”850,是您看到的错误解码字符 ÓÔ¨þchcp 1252 确实帮助正确打印。 print(f.__doc__) 正确显示文档字符串。

标签: windows unicode python-3.7 interactive docstring


【解决方案1】:

help() 有两个错误,其中寻呼机的实现是写入临时文件并将外壳输出到more。来自pydoc.py

def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    with open(filename, 'w', errors='backslashreplace') as file:
        file.write(text)
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename)

文件以默认文件编码(美国和西欧 Windows 上为cp1252)打开,不支持 Windows-1252 字符集以外的字符(例如,不要制作中文帮助文档),然后使用命令(在本例中为more)来处理分页。 more 使用终端的编码(OEM ANSI:在西欧默认为 cp850,在美国默认为 cp437),因此对于 ASCII 集之外的大多数字符,帮助看起来会损坏。

使用chcp 1252 更改终端代码页将正确打印字符:

C:\>chcp 850
Active code page: 850

C:\>py -i test.py
àâùç
>>> help(f)
Help on function f in module __main__:

f()
    ÓÔ¨þ

>>> ^Z


C:\>chcp 1252
Active code page: 1252

C:\>py -i test.py
àâùç
>>> help(f)
Help on function f in module __main__:

f()
    àâùç

>>>

【讨论】:

  • 谢谢,它在 Windows 10,python 3.7 上运行良好。奇怪的是(我相信)它不适用于 Windows 7 机器上的 python 3.4,它还破坏了 printed 输出。不过没关系!
猜你喜欢
  • 2010-11-19
  • 2017-06-09
  • 2019-05-18
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多