Discuss / Python / UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 2: invalid continuation byt

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 2: invalid continuation byt

Topic source

ywjco_567

#1 Created at ... [Delete] [Delete and Lock User]

运行课程的例子,提示“UnicodeDecodeError”

试了一下先用print(output):

print('$ nslookup')

p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

output, err = p.communicate(b'set q=mx\npython.org\nexit\n')

print(output)

print(output.decode('utf-8'))

问题是出现了utf-8不能解码的字节:\xc8。将出错信息拷到网上查,发现:encoding = 'gbk'就能解决问题。

GBK,又称GBK大字符集,是将所有亚洲文字的双字节字符,包括简体中文、繁体中文、日语、韩语等,都使用一种格式编码,兼容所有平台的上的语言。GBK大字符集包含的汉字数量比GB2312和BIG5多,使得汉字兼容足够使用。   

最后:

print('$ nslookup')

p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

output, err = p.communicate(b'set q=mx\npython.org\nexit\n')

# print(output.decode('utf-8'))

print(output.decode('gbk'))

print('Exit code:', p.returncode)


  • 1

Reply