Python 语法错误:文件中出现非 ASCII 字符'\xe2'。

9

我刚刚从使用Python 3运行Django应用程序转换为使用Python 2.7。现在出现了以下错误:

SyntaxError: Non-ASCII character '\xe2' in file /Users/user/Documents/workspace/testpro/testpro/apps/common/models/vendor.py on line 9, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

它所指的代码只是一条注释:
class Vendor(BaseModel):
    """
    A company manages owns one of more stores.‎
    """
    name = models.CharField(max_length=255)


    def __unicode__(self):
        return self.name

为什么?

这个是有效的:

 class Vendor(BaseModel):
        """

        """
        name = models.CharField(max_length=255)


        def __unicode__(self):
            return self.name

1
你读过相关的 PEP 文件了吗? - Martijn Pieters
1
你的发布代码中没有任何注释。你有一个文档字符串 - Martijn Pieters
@LukasGraf:我正在尝试查找一个可能在位置E2使用某种非断空格的编解码器,但我还没有找到一个。 - Martijn Pieters
@LukasGraf:发布的代码中有一个\xe2\x80\x8e序列。 - Martijn Pieters
1
我刚刚注意到了,我的错。@Spike,请忽略我的评论。 - Lukas Graf
显示剩余2条评论
2个回答

12

您的文档字符串中有一个UTF-8编码的U+200E从左到右标记

'\n    A company manages owns one of more stores.\xe2\x80\x8e\n    '

要么从代码中删除该码点(并尝试使用代码编辑器而不是文字处理软件),要么只需在文件顶部放置PEP-263编码注释:

要么从代码中删除该码点(并尝试使用代码编辑器而不是文字处理软件),要么只需在文件顶部放置PEP-263编码注释:

# encoding=utf8

Python 3 默认使用 UTF-8 编码,而 Python 2 的源代码默认为 ASCII 编码(除非您添加了相关注释)。


0

正如Martijn Pieters指出的那样,你的文档字符串包含UTF-8(即非ASCII)字符。

我想进一步阐述一下声明文件编码的正确方法。正如PEP 263所述:

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

# coding=<encoding name>

or (using formats recognized by popular editors):

#!/usr/bin/python
# -*- coding: <encoding name> -*-

or:

#!/usr/bin/python
# vim: set fileencoding=<encoding name> : 

More precisely, the first or second line must match the following regular expression:

^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)

这意味着什么(正如在回答另一个问题中明确概括的):

因此,你可以在“编码”部分之前放置几乎任何内容,但如果你想要100%符合Python文档建议,请坚持使用“编码”(没有前缀)。

因此,在这种情况下,建议使用“魔术注释”:

# coding=utf8

或者:

#!/usr/bin/python
# -*- coding: utf8 -*-

或者:

#!/usr/bin/python
# vim: set fileencoding=utf8 :

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接