Python SyntaxError:fi中的非ASCII字符'\xe2'

2024-04-24 16:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚从在Python3下运行Django应用程序切换到使用Python2.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

Tags: djangonameselfreturnmodelsdefunicodelength
2条回答

您的docstring中有一个UTF-8编码的U+200E LEFT-TO-RIGHT MARK

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

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

# encoding=utf8

Python 3默认使用UTF-8,Python 2默认使用ASCII作为源代码,除非您添加了该注释。

正如已经由Martijn Pieters通过pointed out一样,docstring包含一个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]+)

这意味着什么(用answer to another question来概括):

So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.

因此,就本案而言,建议的“神奇评论”是:

# coding=utf8

或:

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

或:

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

相关问题 更多 >