use*_*723 6 python html5 cgi utf-8 python-3.x
对于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>
""")
Run Code Online (Sandbox Code Playgroud)
此代码不起作用.
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head></head>
<body>
?ö??çü
</body>
</html>
""")
Run Code Online (Sandbox Code Playgroud)
但这个代码有效.
Mar*_*ers 10
对于CGI,使用print()要求已为输出设置了正确的编解码器.print()写入sys.stdout并sys.stdout已使用特定编码打开,如何确定是依赖于平台的,并且可以根据脚本的运行方式而有所不同.将脚本作为CGI脚本运行意味着您几乎不知道将使用什么编码.
在您的情况下,Web服务器已将文本输出的语言环境设置为UTF-8以外的固定编码.Python使用该语言环境设置以该编码生成输出,并且没有<meta>标题,您的浏览器正确猜测该编码(或服务器已在Content-Type标头中传达它),但是使用<meta>标题您告诉它使用不同的编码,对生成的数据不正确.
sys.stdout.buffer在明确编码为UTF-8之后,您可以直接写入.创建一个帮助函数,使这更容易:
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>
""")
Run Code Online (Sandbox Code Playgroud)
另一种方法是替换使用您需要的编解码器sys.stdout的新io.TextIOWrapper()对象:
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>
""")
Run Code Online (Sandbox Code Playgroud)
小智 10
来自https://ru.stackoverflow.com/a/352838/11350
首先不要忘记在文件中设置编码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)
然后试试
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用apache2,请添加到您的conf.
AddDefaultCharset UTF-8
SetEnv PYTHONIOENCODING utf8
Run Code Online (Sandbox Code Playgroud)