简体   繁体   English

在CentOS 5.8中打开Python文件中的UnicodeEncodeError

[英]UnicodeEncodeError in Python file open on CentOS 5.8

I have a problem with file open() in Python on 32 bit CentOS 5.8. 我在32位CentOS 5.8上的Python中的open()文件有问题。 When using characters outside of ascii in a filename I get the following error: 在文件名中使用ascii之外的字符时,出现以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 88: ordinal not in range(128)

The offending line is 冒犯的行是

file = open(full_path, 'w')

The code works fine on 64 bit Ubuntu 12.10 and 64 bit CentOS 6.3. 该代码可在64位Ubuntu 12.10和64位CentOS 6.3上正常运行。

Some information from the server where the error happens: 来自发生错误的服务器的一些信息:

$ python --version
Python 2.7.3
$ cat /etc/redhat-release 
CentOS release 5.8 (Final)
$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

I have checked that on the Ubuntu machine the type of the "full_path" variable is 'unicode'. 我已经检查了在Ubuntu机器上“ full_path”变量的类型是“ unicode”。 Part of the "full_path" variable comes from a configuration file in UTF-8 format. “ full_path”变量的一部分来自UTF-8格式的配置文件。 The rest from a web page in UTF-8 format. 其余的内容来自UTF-8格式的网页。

I have not done any testing on the CentOS 5.8 machine yet as it is the production server I would rather not do random testing on it. 我尚未在CentOS 5.8机器上进行任何测试,因为它是生产服务器,所以我不想在它上进行随机测试。 Any hints to what can be the reason for this error is appreciated. 任何暗示可能是导致此错误的原因的提示均应受到赞赏。

Update 更新资料

If forgot to mention that the following works: 如果忘记提及以下工作:

$ python
Python 2.7.3 (default, Jun 11 2012, 22:26:11) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open(u'ø.txt', 'w')
>>>

Which in my head should be the same as the actual program, but apparently it isn't. 我认为哪个应该与实际程序相同,但显然不是。

Update 2 更新2

Now it works for some reason. 现在它由于某种原因而起作用。 The program is a Turbogears web app and I just started and stopped the server daemon to see the result of some debug printing and the error no longer happens. 该程序是Turbogears Web应用程序,我刚刚启动和停止了服务器守护程序,以查看某些调试打印的结果,并且错误不再发生。

I am still at loss for why this happens, but at least the problem is temporarily resolved. 我仍然不知道为什么会发生这种情况,但是至少问题是暂时解决的。

I'm not sure if this will work as a solution, but i had a error like that. 我不确定这是否可以作为解决方案,但我有这样的错误。 I solved it, but i have some side effects now (look at my profile). 我解决了,但是我现在有一些副作用(请看我的个人资料)。 Try: 尝试:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM