Windows下Python subprocess获取netsh输出的编码错误问题
解决subprocess执行netsh命令的UnicodeDecodeError问题
问题描述
执行Windows命令netsh wlan show interfaces获取无线网卡信息时,使用utf-8编码解码subprocess输出触发UnicodeDecodeError,相关代码及报错信息如下:
原代码
import subprocess class LocalNetwork: def networkinformations(): result = subprocess.check_output('netsh wlan show interfaces',shell=True,encoding='utf-8').strip().splitlines() print(result) LocalNetwork.networkinformations()
报错回溯
Traceback (most recent call last): File "d:\Python\Bibliotheken\NetyPy.py", line 8, in <module> LocalNetwork.networkinformations() File "d:\Python\Bibliotheken\NetyPy.py", line 5, in networkinformations result = sub.check_output('netsh wlan show interfaces', shell=True, encoding='utf-8').strip().splitlines() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 466, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 550, in run stdout, stderr = process.communicate(input, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\subprocess.py", line 1196, in communicate stdout = self.stdout.read() ^^^^^^^^^^^^^^^^^^ File "<frozen codecs>", line 322, in decode UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 285: invalid start byte
解决方案
Windows终端默认编码并非utf-8,通常为GBK或cp1252(依系统语言而定),以下是几种可行的解决方式:
直接指定Windows兼容编码
将encoding参数改为gbk或cp1252,适配终端输出编码:import subprocess class LocalNetwork: def networkinformations(): result = subprocess.check_output('netsh wlan show interfaces', shell=True, encoding='gbk').strip().splitlines() print(result) LocalNetwork.networkinformations()先获取字节流再解码
先获取原始字节数据,再用正确编码解码,避免编码参数冲突:import subprocess class LocalNetwork: def networkinformations(): byte_result = subprocess.check_output('netsh wlan show interfaces', shell=True) result = byte_result.decode('gbk').strip().splitlines() print(result) LocalNetwork.networkinformations()自动适配系统编码
通过locale模块获取系统默认编码,动态设置解码方式:import subprocess import locale class LocalNetwork: def networkinformations(): system_encoding = locale.getpreferredencoding() result = subprocess.check_output('netsh wlan show interfaces', shell=True, encoding=system_encoding).strip().splitlines() print(result) LocalNetwork.networkinformations()
内容的提问来源于stack exchange,提问作者Wolf Eberhardt
相关产品推荐
相关产品推荐

