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格式的内容?
注意:
.py文件以UTF8编码保存。
有趣的事实:运行
#!/usr/bin/python3
import sys
print("Content-Type: text/plain;charset=utf-8\n")
print(str(sys.stdout.encoding))
从命令行给出 UTF-8
但 运行 它通过 mod_cgi
在 http://example.com/app.py.
中输出 ANSI_X3.4-1968
设置export PYTHONIOENCODING=utf8
没有改变任何东西,可能是因为它是Apache + mod_cgi调用这个Python代码。
简单的解决方案
只需添加:
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
如果你创建这个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格式的内容?
注意:
.py文件以UTF8编码保存。
有趣的事实:运行
#!/usr/bin/python3 import sys print("Content-Type: text/plain;charset=utf-8\n") print(str(sys.stdout.encoding))
从命令行给出
中输出UTF-8
但 运行 它通过mod_cgi
在 http://example.com/app.py.ANSI_X3.4-1968
设置
export PYTHONIOENCODING=utf8
没有改变任何东西,可能是因为它是Apache + mod_cgi调用这个Python代码。
简单的解决方案
只需添加:
SetEnv PYTHONIOENCODING utf8
在 .htaccess
中,连同:
Options +ExecCGI
AddHandler cgi-script .py
另见
替代解决方案
对于 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