python打印中文异常

一、背景

脚本里需要打印中文内容。

二、脚本

1
2
3
4
5
6
7
8
'''
Created on Apr 27, 2016
@author: yeshaoting
'''
if __name__ == '__main__':
print '你好,python!'

三、问题

python脚本里包含有中文时,报如下错误:

1
2
3
4
5
6
7
Traceback (most recent call last):
File "/Applications/STS.app/Contents/Eclipse/plugins/org.python.pydev_4.5.5.201603221110/pysrc/pydevd.py", line 1529, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/STS.app/Contents/Eclipse/plugins/org.python.pydev_4.5.5.201603221110/pysrc/pydevd.py", line 936, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/yeshaoting/java/workspace/python-workspace/HelloPython/base/HelloWorld.py", line 8
SyntaxError: Non-ASCII character '\xe4' in file /Users/yeshaoting/java/workspace/python-workspace/HelloPython/base/HelloWorld.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

四、解决方法

告诉python解释器,按照utf-8编码读取源代码。

具体做法:在python脚本开头添加如下内容:

1
#coding=utf-8

或者:

1
#-*- coding: utf-8 -*-

:此内容必须放在脚本shebang后一行(不允许隔空行)或者放在脚本第一行。

实例

1
2
3
4
#!/usr/bin/python
#coding=utf-8
print "你好,世界";

六、参考文档

Python 中文编码
也谈 Python 的中文编码处理

文章目录
  1. 一、背景
  2. 二、脚本
  3. 三、问题
  4. 四、解决方法
  5. 实例
  6. 六、参考文档
|