2010-02-14 65 views
13

我在Windows XP SP3上运行最新的IPython的Python 2.6,我有两个问题。我的第一个问题是,在IPython下,我无法直接输入Unicode字符串,因此无法使用非拉丁名称打开文件。让我来证明一下。在通常的蟒蛇这下作品:在IPython中输入编码的奇怪问题

>>> sys.getdefaultencoding() 
'ascii' 
>>> sys.getfilesystemencoding() 
'mbcs' 
>>> fd = open(u'm:/Блокнот/home.tdl') 
>>> print u'm:/Блокнот/home.tdl' 
m:/Блокнот/home.tdl 
>>> 

顺便说一句,这是西里尔。而IPython的下我得到:

In [49]: sys.getdefaultencoding() 
Out[49]: 'ascii' 

In [50]: sys.getfilesystemencoding() 
Out[50]: 'mbcs' 

In [52]: fd = open(u'm:/Блокнот/home.tdl') 
--------------------------------------------------------------------------- 
IOError         Traceback (most recent call last) 

C:\Documents and Settings\andrey\<ipython console> in <module>() 

IOError: [Errno 2] No such file or directory: u'm:/\x81\xab\xae\xaa\xad\xae\xe2/home.tdl' 

In [53]: print u'm:/Блокнот/home.tdl' 
-------------->print(u'm:/Блокнот/home.tdl') 
ERROR: An unexpected error occurred while tokenizing input 
The following traceback may be corrupted or invalid 
The error message is: ('EOF in multi-line statement', (15, 0)) 

--------------------------------------------------------------------------- 
UnicodeEncodeError      Traceback (most recent call last) 

C:\Documents and Settings\andrey\<ipython console> in <module>() 

C:\Program Files\Python26\lib\encodings\cp866.pyc in encode(self, input, errors) 
    10 
    11  def encode(self,input,errors='strict'): 
---> 12   return codecs.charmap_encode(input,errors,encoding_map) 
    13 
    14  def decode(self,input,errors='strict'): 

UnicodeEncodeError: 'charmap' codec can't encode characters in position 3-9: character maps to <und 

In [54]: 

第二个问题是少折腾,但仍。当我尝试打开文件并将文件名参数指定为非unicode字符串时,它不会打开。我必须从OEM字符集强行解码串,我还没来得及打开的文件,这是非常不方便:

>>> fd2 = open('m:/Блокнот/home.tdl'.decode('cp866')) 
>>> 

或许这东西与我的区域设置,我不知道,因为我可以”甚至可以从控制台剪切并粘贴西里尔字母文本。我在区域环境中到处放置了“俄罗斯”,但似乎并不奏效。

回答

12

是的。在控制台输入Unicode始终是有问题的,通常最好避免,但是IPython is particularly broke。它将您在控制台上键入的字符转换为ISO-8859-1中编码的字符,而不管您给出的实际编码如何。现在,你必须说u'm:/\u0411\u043b\u043e\u043a\u043d\u043e\u0442/home.tdl'

+0

哦,好的。虽然这很可悲。将等待修复。 – 2010-02-14 12:08:51

+3

这是针对此问题的补丁https://bugs.launchpad.net/ipython/+bug/339642 只需从IPython发行版中的iplib.py中删除行'source = source.encode(self.stdin_encoding)'即可。它在OS X中为我工作。 – 2010-04-26 16:48:55

+0

@ t0ster:谢谢你的提示,为我工作。并认为我花了几个小时Google搜索认为这是一个Matplotlib的问题。 – Halka 2011-03-21 21:27:14

1

事与愿违的是,这将工作:

fd = open('m:/Блокнот/home.tdl') 

或者:

fd = open('m:/Блокнот/home.tdl'.encode('utf-8')) 

这得到周围IPython中的漏洞,通过输入字符串作为原料UTF-8编码的字节串。 ipython不会尝试任何有趣的业务。如果你愿意,你可以自由地将它编码成一个unicode字符串,并继续你的生活。