Discuss / Python / decode 提示出错 Windows系统

decode 提示出错 Windows系统

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'))#这一行提示decode出错 为什么呢
print('Exit code:', p.returncode)

时金岁月

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

我看网上别人说是因为解释器不支持utf-8这种模式,但是我们在开头不是声明了嘛,# -*- coding:utf-8 -*-   为啥还不行,不是很理解;然后按照他们的说法,改成了print(output.decode('unicode_escape'))确实不报错了。

范伟

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

设置电脑的语言,语言和时间界面---管理语言设置---更改系统区域设置---复选框’Beta版:。。。‘ 打√,重启电脑就ok了

代码前面的coding声明只是允许代码文件使用utf-8,但是你popen是相当于在控制台运行程序,而Windows控制台使用的编码默认是gbk,所以子进程输出的内容是gbk编码,需要.decode('gbk')


  • 1

Reply