在WindowsCMD和pycharm上用Python 2.7.5.1进行编码和解码,得到了不同的结果

在WindowsCMD和pycharm上用Python 2.7.5.1进行编码和解码,得到了不同的结果,python,string,unicode,decode,encode,Python,String,Unicode,Decode,Encode,我使用此代码处理中文: # -*- coding: utf-8 -*- strInFilNname = u'%s' % raw_input("input fileName:").decode('utf-8') pathName = u'%s' % raw_input("input filePath:").decode('utf-8') 当我在PyCharm上运行时,一切都正常。但当我在windows CMD上运行此命令时,我得到以下错误代码: Traceback (most

我使用此代码处理中文:

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

  strInFilNname = u'%s' % raw_input("input fileName:").decode('utf-8')

  pathName = u'%s' % raw_input("input filePath:").decode('utf-8')
当我在PyCharm上运行时,一切都正常。但当我在windows CMD上运行此命令时,我得到以下错误代码:

 Traceback (most recent call last):
 File "E:\Sites\GetAllFile.py", line 23, in <module>
 strInFilNname = u'%s' % raw_input("input filename:").decode('utf-8')
 File "E:\Portable Python 2.7.5.1\App\lib\encodings\utf_8.py", line 16, in decode
 return codecs.utf_8_decode(input, errors, True)
 UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 0: invalid continuation byte
我读过这篇文章,但找不到有效的解决方案


我真的想知道为什么会这样。

Windows控制台编码不是UTF-8。我假设您使用的是中文本地化版本的Windows,因为您在Python 3.3中提到错误会消失,并建议尝试sys.stdin.encoding而不是utf-8

下面是一个来自my US本地化窗口的示例,使用cp437代码页中的字符,美国控制台使用Python 2.7.9:

这将返回控制台编码中的字节字符串:

>>> raw_input('test? ')
test? │┤╡╢╖╕╣
'\xb3\xb4\xb5\xb6\xb7\xb8\xb9'
转换为Unicode:

>>> import sys
>>> sys.stdin.encoding
'cp437'
>>> raw_input('test? ').decode(sys.stdin.encoding)
test? │┤╡╢╖╕╣║╗╝╜╛
u'\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b'
注意,它可以正确打印:

>>> print(raw_input('test? ').decode(sys.stdin.encoding))
test? │┤╡╢╖╕╣║╗
│┤╡╢╖╕╣║╗
这适用于中文Windows控制台,并且将使用正确的中文控制台编码。以下是将我的系统切换为中文后的相同代码:

>>> raw_input('Test? ')
Test? 我是美国人。
'\xce\xd2\xca\xc7\xc3\xc0\xb9\xfa\xc8\xcb\xa1\xa3'
>>> import sys
>>> sys.stdin.encoding
'cp936'
>>> raw_input('Test? ').decode(sys.stdin.encoding)
Test? 我是美国人。
u'\u6211\u662f\u7f8e\u56fd\u4eba\u3002'
>>> print raw_input('Test? ').decode(sys.stdin.encoding)
Test? 我是美国人。
我是美国人。
Python 3.3使这一点更加简单:

>>> input('Test? ')
Test? 我是美国人。
'我是美国人。'

Windows命令提示符不支持Unicode输出。急停。有各种各样的建议来解决这个问题,例如使用chcp,但它们充其量是笨重的,通常不可用。现在最好的建议是不要使用它来支持Unicode输出的控制台,例如IDLE、IDE控制台、Powershell等。谢谢。但是当我使用相同的代码并在python 3.3的CMD上运行时,错误也会消失,为什么呢?错误可能会消失,但输出不正确,而不是预期的Unicode输出。您可以通过一些技巧使错误消失—查看pythoniocodeding或替换sys.stdout,但即使这样做,Windows命令提示符显示的内容也将不正确,或者不符合您的预期。在Win10 pt\BR上不起作用。sys.stdin.encoding返回utf-8,解码简单地分解…@j4x您使用的Python版本是什么?这是一个4年前的答案,编码非常适合Python和操作系统。Hi@MarkTolonen。它是一个ActiveState Python 2.7.14。谢谢你的关注@j4x使用任何类型的GUI?它们可以覆盖标准输入/输出和。编码可能不正确。