对于HTML5和Python CGI:
如果我写UTF-8元标签,我的代码就不能工作。如果我不写,它就会起作用。
页面编码为UTF-8。
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
şöğıçü
</body>
</html>
""")这个代码不起作用。
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head></head>
<body>
şöğıçü
</body>
</html>
""")但是这个代码是有效的。
发布于 2013-02-14 02:33:53
对于CGI,使用print()需要为输出设置正确的编解码器。print()对sys.stdout和sys.stdout的写入是使用特定的编码打开的,如何确定该编码取决于平台,并且可以根据脚本的运行方式而有所不同。将脚本作为CGI脚本运行意味着您几乎不知道将使用什么编码。
在您的示例中,web服务器已将文本输出的区域设置设置为UTF-8以外的固定编码。Python使用该区域设置以该编码生成输出,如果没有<meta>标头,浏览器将正确猜测该编码(或者服务器在Content-Type标头中传递了该编码),但是使用<meta>标头,您将告诉它使用不同的编码,该编码对于生成的数据是不正确的。
在显式编码为UTF-8之后,您可以直接写入sys.stdout.buffer。创建一个helper函数来简化此操作:
import sys
def enc_print(string='', encoding='utf8'):
sys.stdout.buffer.write(string.encode(encoding) + b'\n')
enc_print("Content-type:text/html")
enc_print()
enc_print("""
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
şöğıçü
</body>
</html>
""")另一种方法是用使用所需编解码器的新io.TextIOWrapper() object替换sys.stdout:
import sys
import io
def set_output_encoding(codec, errors='strict'):
sys.stdout = io.TextIOWrapper(
sys.stdout.detach(), errors=errors,
line_buffering=sys.stdout.line_buffering)
set_output_encoding('utf8')
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head></head>
<body>
şöğıçü
</body>
</html>
""")发布于 2015-05-28 06:53:00
来自https://ru.stackoverflow.com/a/352838/11350
首先,不要忘记在文件中设置编码
#!/usr/bin/env python
# -*- coding: utf-8 -*-然后试一试
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())或者,如果您使用apache2,则将其添加到您的conf中。
AddDefaultCharset UTF-8
SetEnv PYTHONIOENCODING utf8https://stackoverflow.com/questions/14860034
复制相似问题