unicode - Python 3 CGI : how to output raw bytes

标签 unicode encoding utf-8 python-3.x webserver

我决定使用 Python 3 来制作我的网站,但是我遇到了 Unicode 输出的问题。

看起来很普通print(html) #html is a str应该工作,但事实并非如此。我收到 UnicodeEncodeError: 'ascii' codec can't encode characters[...]: ordinal not in range(128) .这一定是因为网络服务器不支持 unicode 输出。

我尝试的下一件事是 print(html.encode('utf-8')) ,但我得到了类似字节字符串的 repr 输出:它被放置在 b'...' 中并且所有转义字符都是原始格式(例如 \n\xd0\x9c )

请告诉我在 Python 3.1 中将 Unicode (str) 字符串输出为原始 UTF-8 编码字节字符串的正确方法

最佳答案

这里的问题是您的 stdout 未连接到实际终端,默认情况下将使用 ASCII 编码。因此,您需要写入 sys.stdout.buffer,它是 sys.stdout 的“原始”二进制输出。这可以通过多种方式完成,最常见的一种似乎是:

import codecs, sys
writer = codecs.getwriter('utf8')(sys.stdout.buffer)

和使用作家。在 CGI 脚本中,您可以将 sys.stdout 替换为 writer,因此:
sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)

可能确实有效,因此您可以正常打印。试试吧!

关于unicode - Python 3 CGI : how to output raw bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5515007/

相关文章:

将 Unicode 代码点转换为 UTF-8 和 UTF-32

hadoop - 在 hadoop 中编码为 UTF-8 文件

Python:将utf8字符串转换为�的最简单方法是什么?

unicode - Font Awesome 和 CSS 伪元素 - 某些 unicode 字符不起作用

python-3.x - 使用 Python 请求库将 unicode 字符串发布到 Web 服务

c# - WebClient.DownloadString 结果与浏览器结果 2 不匹配

python - 在python文件中使用像 'ë'和 'ç'这样的字符

PHP 导出带有 BOM 的 CSV UTF-8 不起作用

linux - 在 Ubuntu 中分配未使用的 Unicode 字符

c++ - 使用 Unicode C++ 的飞机符号