python PEP263

https://www.python.org/dev/peps/pep-0263/

SyntaxError
Non-ASCII character ‘\xe5’ in file D:\python_work\electric_car_1.py on line 23, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

本来可以正常run的py文件突然这样提示error,去官网看下解决方法。

原因
In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding “unicode-escape”. This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the “unicode-escape” encoding for Unicode literals.
在Python 2.1中,Unicode文字只能使用基于Latin-1的编码“unicode-escape”编写。这使得编程环境对在非拉丁语1语言环境中生活和工作的Python用户非常不友好,例如许多亚洲国家。程序员可以使用喜欢的编码来编写他们的8位字符串,但是绑定到Unicode文字的“unicode-escape”编码。
解决方法
I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.
我建议在每个源文件的基础上使Python源代码编码可见和可更改,方法是使用文件顶部的特殊注释来声明编码。
Python will default to ASCII as standard encoding if no other encoding hints are given.
如果没有给出其他编码提示,Python将默认为ASCII作为标准编码。

在py文件开头加上:

1
2
#!/usr/bin/python
# -*- coding: UTF-8 -*-