只需添加:
SetEnv PYTHONIOENCODING utf8
在中.htaccess
,以及:
Options +ExecCGI
AddHandler cgi-script .py
另请参见使用apache服务器和Problèmepython apache et utf8时覆盖python3默认编码器。也相关但没有答案可以直接解决:在Python 3 CGI脚本中设置编码。
对于Python 3-3.6(请参阅如何在Python 3中设置sys.stdout编码?):
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