Python3.7 & Windows :交互模式下文档字符串中的 unicode 字符不正确

Python3.7 & Windows : incorrect unicode characters in docstrings in interactive mode

将以下程序保存为 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()
    ����

是否有任何(简单的)解决方法?

help() 有两个错误,寻呼机的实现是写入一个临时文件,shell 输出到 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)

文件使用默认文件编码打开(cp1252 on U.S。和西欧 Windows)不支持 Windows-1252 之外的字符字符集(例如,不要制作中文帮助文档),然后 shell 输出到命令(在本例中为 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()
    àâùç

>>>