管道Python程序的输出时,Python解释器会对编码感到困惑,并将其设置为None.这意味着这样的程序:
# -*- coding: utf-8 -*-
print u"åäö"
Run Code Online (Sandbox Code Playgroud)
正常运行时会正常工作,但失败时:
UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ xa0'进行编码:序数不在范围内(128)
当在管道序列中使用时.
在配管时使这项工作的最佳方法是什么?我可以告诉它使用shell/filesystem /无论使用什么编码吗?
到目前为止我看到的建议是直接修改你的site.py,或者使用这个hack对defaultencoding进行硬编码:
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法使管道工作?
当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....错误.我认为这是因为Windows控制台不接受仅Unicode字符.最好的方法是什么??在这种情况下,有什么方法可以让Python自动打印而不是失败?
编辑: 我正在使用Python 2.5.
注意: @ LasseV.Karlsen回答带有复选标记有点过时(从2008年开始).请谨慎使用下面的解决方案/答案/建议!!
截至今天(2016年1月6日),@ JFSebastian答案更为相关.
在Python 2中设置默认输出编码是一个众所周知的习惯用法:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
Run Code Online (Sandbox Code Playgroud)
这将sys.stdout对象包装在编解码器编写器中,该编解码器编写器以UTF-8编码输出.
但是,这种技术在Python 3中不起作用,因为sys.stdout.write()期望a str,但是编码的结果是bytes,并且当codecs尝试将编码的字节写入原始时发生错误sys.stdout.
在Python 3中执行此操作的正确方法是什么?
为什么这不起作用的任何想法?我真的认为'忽略'会做正确的事.
>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud) 我正在使用pyserial并需要发送一些小于255的值.如果我发送int本身,则发送int的ascii值.所以现在我将int转换为unicode值并通过串口发送.
unichr(numlessthan255);
However it throws this error:
'ascii' codec can't encode character u'\x9a' in position 24: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
什么是将int转换为unicode的最佳方法?
我在同一个项目中使用windows和linux机器.Windows上stdin的默认编码是cp1252,linux上的默认编码是utf-8.
我想把一切都变成uft-8.可能吗?我该怎么做?
我正在尝试将符号写入?python中的文本文件.我认为它与编码有关(utf-8).这是代码:
# -*- coding: utf-8 -*-
outFile = open('./myFile.txt', 'wb')
outFile.write("?")
outFile.close()
Run Code Online (Sandbox Code Playgroud)
而不是"?"我得到的黑色"â—".我怎样才能解决这个问题?
有人可以向我解释为什么python有这种行为吗?
我来解释吧.
背景
我有一个python安装,我想使用一些不在ASCII表中的字符.所以我改变了我的python默认enconding.我以这种方式将每个字符串保存到文件.py中'_MAIL_TITLE_': u'???????????? ???????',
现在,使用替换我的字典键的方法,我想以动态的方式将html模板插入到我的字符串中.
我放入html页面的标题:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
...... <!-- Some Css's -->
</head>
Run Code Online (Sandbox Code Playgroud)
不幸的是,我的html doc来找我(在那些替换之后)有一些错误的字符(未转换?错误转换?)
所以,我打开一个终端并开始做一些订单:
1 - Python 2.4.6 (#1, Jan 27 2012, 15:41:03)
2 - [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
3 - Type "help", "copyright", "credits" or "license" for more information.
4 - >>> import sys
5 - >>> sys.getdefaultencoding()
6 - 'utf-8'
7 - >>> u'èéòç'
8 - u'\xe8\xe9\xf2\xe7'
9 - >>> u'èéòç'.encode('utf-8')
10 - '\xc3\xa8\xc3\xa9\xc3\xb2\xc3\xa7'
11 …Run Code Online (Sandbox Code Playgroud)