简体   繁体   English

utf-8 编码在 iPython 控制台中工作,而不是在 Spyder 编辑器中

[英]utf-8 encoding works in iPython console, not in Spyder editor

here is the minimal test.这是最小的测试。 in Spyder Editor, I wrote these 4 lines (nothing else)在 Spyder Editor 中,我写了这 4 行(仅此而已)

# -*- coding: utf-8 -*-
import sys
print(sys.getdefaultencoding() )
print(u"µ")

I get:我得到:

utf-8
µ

but if I just copy-paste the 2 lines in iPython console, I get但如果我只是在 iPython 控制台中复制粘贴这两行,我会得到

utf-8 \n µ

what's wrong with my.py file or with spyder Editor? my.py 文件或 spyder 编辑器有什么问题?

what's wrong with my.py file or with spyder Editor? my.py 文件或 spyder 编辑器有什么问题?

The problem is most likely that you're using Windows and the console interprets your output as Windows-1252 (the default console encoding for western european windows):问题很可能是您正在使用 Windows 并且控制台将您的 output 解释为 Windows-1252(西欧窗口的默认控制台编码):

>>> 'µ'.encode('utf-8').decode('windows-1252')
'µ'

It's not clear whether the first snippet is the spyder console or a normal python shell in the windows console.目前尚不清楚第一个片段是 spyder 控制台还是 windows 控制台中的普通python shell。

 print(sys.getdefaultencoding() )

has literally nothing to do with anything.从字面上看与任何事情无关。 sys.getdefaultencoding() is the internal python encoding. sys.getdefaultencoding()是内部 python 编码。

You can try to mess with PYTHONIOENCODING , or see what locale.getpreferredencoding() returns.您可以尝试弄乱PYTHONIOENCODING ,或者查看locale.getpreferredencoding()返回的内容。

I solved the problem, thanks to @Carlos Cordoba (Spyder's master).感谢@Carlos Cordoba(Spyder 的大师),我解决了这个问题。

I opened the file in notepad++ , and converted it into " UTF-8 BOM " (it was in UTF-8 but without BOM)我在notepad++中打开文件,并将其转换为“ UTF-8 BOM ”(它在 UTF-8 但没有 BOM)

Now it works现在它可以工作了

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

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