mod_cgi + utf8 + Python3不产生任何输出


问题内容

如果创建此 app.py

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

并通过以下方式启用CGI .htaccess

Options +ExecCGI
AddHandler cgi-script .py

完全可以使用:http :
//example.com/app.py显示“ Hello world!”。

但是,如果添加重音符号:

print("Quel été!")

这不再起作用:浏览器中的输出页面为空。

问题:如何使用Python3 +输出UTF8内容mod_cgi

注意:

  • .py文件以UTF8编码保存。

  • 可能相关:https : //redmine.lighttpd.net/issues/2471

  • 有趣的事实:跑步

    #!/usr/bin/python3
    

    import sys
    print(“Content-Type: text/plain;charset=utf-8\n”)
    print(str(sys.stdout.encoding))

从命令行给出,UTF-8但通过http://example.com/app.py中的mod_cgi输出运行。ANSI_X3.4-1968

设置export PYTHONIOENCODING=utf8没有任何改变,可能是因为Apache + mod_cgi调用了此Python代码。


问题答案:

简单的解决方案

只需添加:

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