python27 UnicodeDecodeError: 'utf8' codec can't decode byte 0xb7 in position 34: invalid 报错解决

python27在windows 命令行窗口中运行代码,我的python程序开头使用了

sys.setdefaultencoding('utf-8')

当我在程序中将 由命令行参数 传来的包含中文名的字符串 解码为 utf-8 格式的时候报错:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xb7 in position 34: invalid

或者
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb9 in position 91: invalid

(因为这个代码 codecs.utf_8_decode(input, errors, True) 导致的错误)

我的解决方案如下( 下面的示例代码中 cmd_input_str 变量 记录命令行接收到的字串 )

save_str = (cmd_input_str.decode('gb2312')).encode('utf-8')

这样写就不会报错了,能成功保存到xml

 

posted @ 2014-11-07 15:17  vily_雷  阅读(2644)  评论(0编辑  收藏  举报