简体   繁体   English

语法错误:第2行的文件G:\\ test.py中的非ASCII字符'\\ xe3',但未声明编码

[英]SyntaxError: Non-ASCII character '\xe3' in file G:\test.py on line 2, but no encoding declared

I have a simple script. 我有一个简单的脚本。

# -*- encoding : utf-8 -*-
episode_title = "ザ・ロック(日本語吹替版)".decode('utf-8')
print episode_title.encode('utf-8')

But it doesn't work at my cmd console (Win8 PC, encoding is big5). 但这在我的cmd控制台(Win8 PC,编码为big5)上不起作用。

SyntaxError: Non-ASCII character '\xe3' in file G:\test.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Although I have change the code page to utf-8 虽然我将代码页更改为utf-8

chcp 65001 

It still doesn't work. 它仍然不起作用。

But when I run it in my IPython notebook, it works! 但是,当我在IPython笔记本中运行它时,它就可以工作了! (Works also in PyCharm and the IPython Qt console) (也可以在PyCharm和IPython Qt控制台中使用)

ザ・ロック(日本語吹替版)

But when I run it in Ubuntu: 但是当我在Ubuntu中运行它时:

aaron@ubuntu:~$ python test.py
  File "test.py", line 2
SyntaxError: Non-ASCII character '\xe3' in file test.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

It surprised me that it cannot run in Ubuntu. 令我惊讶的是它无法在Ubuntu中运行。

Would someone please explain this mystery? 有人可以解释这个谜吗?

Why it run in IPython Notebook or PyCharm? 为什么要在IPython Notebook或PyCharm中运行? but not in CMD or Ubuntu Terminal? 但不是在CMD或Ubuntu Terminal中?

Your comment doesn't fit the requirements of the PEP because you left a space between the word encoding and the colon: 您的评论不符合PEP的要求,因为您在文字encoding和冒号之间留了一个空格:

# -*- encoding : utf-8 -*-
#             ^

The PEP specifies the exact regular expression used to match the declaration: PEP指定用于匹配声明的确切正则表达式:

coding[:=]\s*([-\w.]+)

So Python looks for the literal text coding followed by either a colon : or an equals sign = , followed by zero or more whitespace characters, then followed by the codec. 因此,Python会寻找文字文本coding然后是冒号:或等号= ,然后是零个或多个空格字符,然后是编解码器。

All you need to do is remove that extra space you have: 您需要做的就是删除您拥有的多余空间:

# -*- encoding: utf-8 -*-

The comment applies only when Python has to read the source code from disk; 当Python必须从磁盘读取源代码时,该注释才适用。 in an interactive interpreter you enter your code with a console or terminal that also declares an encoding, through the normal localisation support of the platform. 交互式解释器中,您可以通过平台的常规本地化支持,使用也声明编码的控制台或终端输入代码。 IPython and PyCharm fall under this category; IPython和PyCharm属于这一类别; you keyboard input is correctly decoded using that information and the declaration is not needed. 您会使用该信息正确解码键盘输入,并且不需要声明。

Just replace 只需更换

# -*- encoding : utf-8 -*-

with

# encoding: utf-8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM