mod_cgi + utf8 + Python3不产生任何输出 [英] mod_cgi + utf8 + Python3 produces no output

查看:98
本文介绍了mod_cgi + utf8 + Python3不产生任何输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您创建此app.py

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

,您可以通过以下方式在.htaccess中启用CGI:

and you enable CGI in .htaccess with:

Options +ExecCGI
AddHandler cgi-script .py

完全有效: http://example.com/app.py 显示你好,世界!".

it totally works: http://example.com/app.py displays "Hello world!".

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

However if you add an accented character:

print("Quel été!")

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

this does not work anymore: the output page is empty in the browser.

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

Question: how to output a UTF8 content with Python3 + mod_cgi?

NB:

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

  • the .py file is saved with UTF8 encoding.

可能是相关的: 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,但通过mod_cgi运行它在 http:/中输出ANSI_X3.4-1968/example.com/app.py .

from command-line gives UTF-8 but running it trough mod_cgi outputs ANSI_X3.4-1968 in http://example.com/app.py.

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

Setting export PYTHONIOENCODING=utf8 did not change anything, probably because it's Apache + mod_cgi that calls this Python code.

推荐答案

简便解决方案

只需添加:

SetEnv PYTHONIOENCODING utf8

.htaccess中的

以及:

Options +ExecCGI
AddHandler cgi-script .py

另请参见在使用apache服务器时覆盖python3默认编码器问题Python apache和utf8 .也相关但没有答案可以直接解决:在Python 3 CGI脚本中设置编码.

See also overwrite python3 default encoder when using apache server 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(请参见如何设置sys .stdout在Python 3中编码?):

For Python 3 - 3.6 (see How to set sys.stdout encoding in Python 3?):

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

对于Python 3.7 +:

For 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

这篇关于mod_cgi + utf8 + Python3不产生任何输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆