Discuss / Python / 通过communicate()方法输入问题

通过communicate()方法输入问题

Topic source

为什么在我的电脑上无论是解释器还是命令行都对这段例子代码报错?

例子代码:

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

报错内容:

$ nslookup
Traceback (most recent call last):
  File "F:/Python/process3.py", line 6, in <module>
    print(output.decode('utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 2: invalid continuation byte

命令行和python解释器报错的内容都相同。搞不明白是什么原因。 顺便想请教一下,这一章节到底在讲什么?这些代码都是什么意思?作为一个编程新手看到这些很迷茫。。。

AYDUI

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

<code></codeprint(output.decode(>print(output.decode('utf-8'))</code> 里面的utf-8改成gbk,windows系统的控制台默认gbk编码,有时候就会出现这种问题,Linux上就没有这种问题了

改过来就好了,非常感谢

用IDE也会出现UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 2: invalid continuation byte,因为output的编码是gb2312,利用utf-8解码则会出错。


  • 1

Reply