Skip to main content
 首页 » 编程设计

Python 3.4 在 Apache2 服务器 (Mac) 上导致 UnicodeEncodeError 但在命令行中工作正常

2025年05月04日21myhome

我正在尝试让 Python 3.4 cgi 脚本和 Apache 在浏览器中输出一个“ü”字符(就此而言,任何其他 Unicode 字符都会出现同样的问题)。 python 3.4 cgi 脚本在 Apache 中导致 UnicodeEncodeError,而类似的 python 2.7 代码在同一台服务器上运行良好。脚本 3.4 和 2.7 从命令行都可以正常工作。

这是我在运行 python 3.4 脚本时遇到的错误:

UnicodeEncodeError: 'ascii' 编解码器无法对位置 23 中的字符 '\xfc' 进行编码:序号不在范围内 (128)

这是导致该错误的代码:

#!/usr/local/bin/python3 
# -*- coding: utf-8 -*- 
 
print ("Content-Type: text/html; charset=utf-8\n\n") 
print ("""\ 
<html> 
<head> 
<meta charset="UTF-8"> 
</head> 
<body> 
""") 
 
print ("U umlaut (Python 3.4): ü<br>") 
 
print ("""\ 
</body> 
</html> 
""") 

同一服务器上的以下 Python 2.7 脚本正确显示 ü 和任何其他 Unicode 字符: (所以这不是 Apache 的问题?)

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
 
print "Content-Type: text/html; charset=utf-8\n\n" 
print """\ 
<html> 
<head> 
<meta charset="UTF-8"> 
</head> 
<body> 
""" 
 
print "U umlaut (Python 2.7): ü<br>" 
 
print """\ 
</body> 
</html> 
""" 

这两个脚本都可以在命令行中正常工作。我已经有了

AddDefaultCharset UTF-8 

在我的 httpd.conf 中。

此外,我的语言环境变量设置如下:

LANG="en_US.UTF-8" 
LC_COLLATE="en_US.UTF-8" 
LC_CTYPE="en_US.UTF-8" 
LC_MESSAGES="en_US.UTF-8" 
LC_MONETARY="en_US.UTF-8" 
LC_NUMERIC="en_US.UTF-8" 
LC_TIME="en_US.UTF-8" 
LC_ALL="en_US.UTF-8" 

A 已经在我能想到的所有地方包含了 UTF-8 设置(有时过多)。有谁知道我还能做些什么来让 python 3.4 脚本在浏览器中正确显示 Unicode 字符?谢谢。

请您参考如下方法:

我知道你的问题已经过了几个月了,但我遇到同样的问题时无意中发现了它。我找到了解决方案。也许它对您没有帮助,但对其他寻求者没有帮助。

Jack O'Connor's solution fixed the problem for me试试这个:

import sys 
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1) 
print("日本語") 
# Also works with other methods of writing to stdout: 
sys.stdout.write("日本語\n") 
sys.stdout.buffer.write("日本語\n".encode())`