Discuss / Python / 遇到代码出错

遇到代码出错

Topic source

caizishuo

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

下面这段代码,不知道为什么就UnicodeError了,我把output打印出来,也没有发现0xc8

import subprocess

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'))
print('Exit code:', p.returncode)

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

caizishuo

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

试了一下ubantu并没有出现该问题

Windows运行环境默认用的字符编码是'gbk',Unix底层的运行环境是'utf-8';

如果你是在Windows环境下运行报错的话,改下解码字符集就可以了:

print(output.decode('gbk'))

x-lql2019

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

请问这段代码在实际中该如何应用?

dalao,为啥我改成gbk后,程序就是直接运行了,啥也没让我输入啊


  • 1

Reply