解决编码方式之间的转换时的报错
1.在使用python2.7做一些就接口测试时,会出现编码报错的问题:
1 Traceback (most recent call last): 2 File "E:/proto_code/Roshan-01-microscript-proto_test-master-src/src/run_all_case.py", line 31, in <module> 3 runner.run(all_case()) 4 File "E:\proto_code\Roshan-01-microscript-proto_test-master-src\src\comment\HTMLTestRunner.py", line 746, in run 5 test(result) 6 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 70, in __call__ 7 return self.run(*args, **kwds) 8 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 108, in run 9 test(result) 10 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 70, in __call__ 11 return self.run(*args, **kwds) 12 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 108, in run 13 test(result) 14 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 70, in __call__ 15 return self.run(*args, **kwds) 16 File "D:\Program Files (x86)\python2.7\lib\unittest\suite.py", line 108, in run 17 test(result) 18 File "D:\Program Files (x86)\python2.7\lib\unittest\case.py", line 393, in __call__ 19 return self.run(*args, **kwds) 20 File "D:\Program Files (x86)\python2.7\lib\unittest\case.py", line 370, in run 21 result.stopTest(self) 22 File "E:\proto_code\Roshan-01-microscript-proto_test-master-src\src\comment\HTMLTestRunner.py", line 670, in stopTest 23 self.complete_output() 24 File "E:\proto_code\Roshan-01-microscript-proto_test-master-src\src\comment\HTMLTestRunner.py", line 645, in complete_output 25 return self.outputBuffer.getvalue() 26 File "D:\Program Files (x86)\python2.7\lib\StringIO.py", line 271, in getvalue 27 self.buf += ''.join(self.buflist) 28 UnicodeDecodeError: 'ascii' codec can't decode byte 0xcd in position 0: ordinal not in range(128)
在解决问题的探寻查询网上博客,发现很多人在说这是编码的问题:“Python在进行编码方式之间的转换时,会将 unicode 作为“中间编码”,但 unicode 最大只有 128 那么长,所以这里当尝试将 ascii 编码字符串转换成"中间编码" unicode 时由于超出了其范围,就报出了如上错误。”
同时网上的很多解决方法是在python文件的前面加上如下代码:
1 import sys 2 defaultencoding = 'utf-8' 3 if sys.getdefaultencoding() != defaultencoding: 4 reload(sys) 5 sys.setdefaultencoding(defaultencoding)
经试验发现,这种方法仅适用于python2.7,在python3中不适用,因为python3已经取消了reload,而在对于编码方法做了很大的调整
https://www.jb51.net/article/111864.htm,参考编码问题详解
如果仍以下错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xcd in position 0: invalid continuation byte
只需要将 defaultencoding 改为:GBK
import sys defaultencoding = 'gbk' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding)
2.在做接口测试时,发现有些入参中文是这样式的:2023%E4%B8%AD%E5%9B%BD%E7%89%9B%E9%80%BC,咋办?
import urllib ch='2023中国牛逼' ch_1=urllib.parse.quote(ch) print('转义前:{},转义后{}'.format(ch,ch_1)) print——转义前:2023中国牛逼,转义后:2023%E4%B8%AD%E5%9B%BD%E7%89%9B%E9%80%BC
作者:小林同学_Scorpio
本博客所有文章仅用于学习、分享和交流目的,欢迎非商业性质转载。
博主的文章没有高度、深度和广度,只是凑字数,做笔记。由于博主的水平不高,不足和错误之处在所难免,希望大家能够批评指出。
博主是利用参考、引用、抄袭、复制和粘贴等多种方式打造成自己的文章,请原谅博主成为一个无耻的文档搬运工!