我决定使用 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/