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

问题描述

将以下程序另存为test.py

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

并以交互模式在Windows cmd窗口中执行它:

python -i test.py

print文字正确,但是当我打电话给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()有两个错误,其中分页器的实现是将其写入临时文件,然后将其外壳化为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字符集以外的字符(例如,不提供中文帮助文档),然后使用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()
    àâùç

>>>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...