4

在开发/本地机器上运行的 Python 代码,但在安装到 Appengine 后失败:

我的文件中的第一行:

# -*- coding: utf8 -*-O

代码后面的行:

s1 = u'Ismerőseid'
logging.info (s1)
s2 = s1 + u':' + s1
logging.info (s2)
logging.info ("%s,%s", s1, s2)

在开发(本地主机)中:

INFO     2012-12-18 04:01:17,926 AppRun.py:662] Ismerőseid,
INFO     2012-12-18 04:01:17,926 AppRun.py:664] Ismerőseid:Ismerőseid
INFO     2012-12-18 04:01:17,926 AppRun.py:665] Ismerőseid,Ismerőseid. Ó,

安装/运行后在 App Engine 上:

I 2012-12-21 06:52:07.730 
É, Á, Ö, Ü. Ó,

E 2012-12-21 06:52:07.736

Traceback (most recent call last):
  File "....", line 672, in xxxx
    s3 = s1 + u':' + s1
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

我尝试过编码/解码/等的各种组合。我还在粘贴的字符串“Ismerőseid”上进行了chardet,它给了我{'confidence': 0.7402600692642154, 'encoding': 'ISO-8859-2'}

任何帮助是极大的赞赏!

4

1 回答 1

6

将这 3 行放在 Python 27 代码的顶部以使用 unicode :

#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# And this code will not give you any problems

s1 = 'É, Á, Ö, Ü. Ó,'
logging.info (s1)
s2 = s1 + ':' + s1
logging.info ("%s,%s", s1, s2)

永远不要用户 str()。只有当你真的需要!

并阅读尼克约翰逊的这篇博文。这是在 Python 27 之前。他没有使用 . from __future__ import unicode_literals,这使得在 Python 中使用 unicode 变得如此简单。

于 2012-12-21T15:47:07.083 回答