Python 2.x获取操作系统的默认编码和UnicodeDecodeError处理

935 views次阅读
没有评论

之前有朋友反馈nagios微信报警插件在处理中文字符的时候会出现问题,因为时间关系这个问题就一直放着。今天抽空解决了下,已经可以正常使用了。具体代码可以详见github,我的github地址:https://github.com/zhangnq/nagios/tree/master/weixin 。这个主要是json库在调用dumps方法时出现了问题。现在加上一个获取操作系统编码的逻辑后测试正常。

在python 2.x中,出现json格式内容前的任何字符串会先decode成unicode格式,默认dumps使用utf8格式。但是如果当输入的字符串编码不是utf8,那么就会出现类似错误了。例如:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xb2 in position 77: invalid start byte

如何获取操作系统的默认编码可以使用这个方法,例如:

sys.stdin.encoding

修改后的代码类似如下:

try:
    data=json.dumps(values)
except:
    import sys
    sys_encoding=sys.stdin.encoding    data=json.dumps(values,encoding=sys_encoding)

在调用dumps方法的时候指定encoding为系统默认编码。

参考连接:
https://stackoverflow.com/questions/25203209/how-to-fix-json-dumps-error-utf8-codec-cant-decode-byte-0xe0-in-position-2
https://stackoverflow.com/questions/37506535/how-to-get-the-system-default-encoding-in-python-2-x

正文完
微信搜一搜“奇悦电脑科技”或扫描二维码关注我们
post-qrcode
 0
章郎虫
版权声明:本站原创文章,由 章郎虫 于2017-05-24发表,共计801字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。