如何在 Python 3 CGI 中打印 unicode 字符?

Har*_*rsh 3 python unicode encoding cgi python-3.x

我正在尝试运行具有一些 Unicode 字符串的 python CGI 脚本。它在控制台中运行良好,但是当我在浏览器中运行它时,它会出现以下错误 -

UnicodeEncodeError: 'ascii' 编解码器无法对位置 198 中的字符 '\u2026' 进行编码:序号不在范围内 (128)

我试过这两个 -
encode('ascii','ignore') unicodedata.normalize('NFKD',var).encode('ascii', 'ignore').strip()
var 是保存 unicode 字符串的变量。

现在如何在浏览器中正确打印 Unicode 或 ascii?

Mar*_*nen 5

当 Python 将 Unicode 字符串打印到控制台时,它通常会检测控制台编码并使用该编码自动对 Unicode 字符串进行编码。对于 CGI 没有终端,所以默认是ascii. 您可以stdout使用以下方法更改为另一种编码:

import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
Run Code Online (Sandbox Code Playgroud)

您也可以使用类似的行stderr