Python 中文注释报错解决方案

今天在学习python的时候注释了一条中文,结果报错:

File “test.py”, line 3
SyntaxError: Non-ASCII character ‘\xe8’ in file test.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

大致意思是说,文件 ‘test.py’ 第三行有问题,是语法错误,并没有ASCII字符,也没有编码声明,请看python官网。

Defining the Encoding
    Python will default to ASCII as standard encoding if no other
    encoding hints are given.

    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=
          # -*- coding:  -*-

官网中大致说:
Python默认使用ASCII标准编码,如果没有其他编码提示,要定义一个源代码编码,下面的格式大家也都看到了,是 coding= encoding name

后来我在 ‘test.py’ 中添加了一行 ‘# -*- coding: utf-8 -*-‘,之后就没有报错了。

[root@hongxue_216 ~]# cat test.py 
#!/usr/bin/python
# -*- coding:utf8 -*-

# 这是注释
print "Hello World!"
[root@hongxue_216 ~]# 
[root@hongxue_216 ~]# ./test.py 
Hello World!
[root@hongxue_216 ~]# 

你可能感兴趣的:(python)