前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Unicode String Parse With Python and Fileinput

Unicode String Parse With Python and Fileinput

作者头像
happy123.me
发布2019-12-30 18:08:52
8150
发布2019-12-30 18:08:52
举报
文章被收录于专栏:乐享123乐享123

用fileinput模块parse数据很方便:

1 2 3 4 5

import fileinput if __name__ == '__main__': for line in fileinput.input(): sys.stdout.write(line)

但有时候会碰到UnicodeDecodeError:

比如执行:

1 2 3 4

echo -e "foo\x80bar" |python3 testinput.py ... UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3: invalid start byte

这种错误还不好用try .. catch忽略掉,因为它是在fileinput模块中自己parse的;

Python2的时候很罗嗦,需要自己用codecs去判断之后,才能parse;

Python3总算是引入了一个openhook参数,可以自己hook处理了;

最简单的处理方式:

1 2 3 4 5 6 7 8

import fileinput import io import sys if __name__ == '__main__': sys.stdin = io.TextIOWrapper(sys.stdin.buffer, errors='replace') for line in fileinput.input(openhook=fileinput.hook_encoded("utf-8")): sys.stdout.write(line)

参考:

https://stackoverflow.com/questions/24754861/unicode-file-with-python-and-fileinput

https://bugs.python.org/issue26756

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档