mod_cgi + utf8 + Python3 没有输出

mod_cgi + utf8 + Python3 produces no output

如果你创建这个app.py

#!/usr/bin/python3
print("Content-Type: text/plain;charset=utf-8\n")
print("Hello World!")

并且您在 .htaccess 中启用 CGI 并使用:

Options +ExecCGI
AddHandler cgi-script .py

完全有效:http://example.com/app.py 显示 "Hello world!"。

但是,如果您添加重音字符:

print("Quel été!")

这不再有效:浏览器中的输出页面为空。

问题:Python3 + mod_cgi如何输出一个UTF8格式的内容?

注意:

简单的解决方案

只需添加:

SetEnv PYTHONIOENCODING utf8

.htaccess 中,连同:

Options +ExecCGI
AddHandler cgi-script .py

另见 and Problème python apache et utf8. Also related but no answers did directly solve it: Set encoding in Python 3 CGI scripts

替代解决方案

对于 Python 3 - 3.6(参见 How to set sys.stdout encoding in Python 3?):

import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

对于 Python 3.7+:

sys.stdout.reconfigure(encoding='utf-8')

注意:即使在某些答案中有时会引用,以下脚本 对 Apache 2.4 + mod_cgi + Python3 不起作用

import locale                                  # Ensures that subsequent open()s 
locale.getpreferredencoding = lambda: 'UTF-8'  # are UTF-8 encoded.
import sys
sys.stdin = open('/dev/stdin', 'r')            # Re-open standard files in UTF-8 
sys.stdout = open('/dev/stdout', 'w')          # mode.
sys.stderr = open('/dev/stderr', 'w') 
print("Content-Type: text/plain;charset=utf-8\n")
print(str(sys.stdout.encoding))  # I still get: ANSI_X3.4-1968