You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中subprocess.check_output处理土耳其/非ASCII字符问题

解决Python subprocess处理Windows系统土耳其字符Wi-Fi名称的问题

问题根源

Windows系统中netsh命令的输出编码并非常见的UTF-8、ISO-8859-9或Windows-1254,而是采用UTF-16LE编码(Windows内核默认的Unicode编码格式),之前指定的编码格式不匹配,导致土耳其字符解码错误、丢失或乱码。

修正后的代码

第一步:正确获取Wi-Fi配置列表

import subprocess

try:
    # 先获取原始字节输出,不指定encoding
    cmd_bytes = subprocess.check_output("netsh wlan show profile", shell=True)
    # 使用UTF-16LE解码,匹配netsh的输出编码
    cmd_output = cmd_bytes.decode('utf-16le')
except subprocess.CalledProcessError as e:
    print(f"命令执行错误: {e}")
    cmd_output = ""

第二步:正确查询带土耳其字符的Wi-Fi配置

提取Wi-Fi名称后,执行查询命令时同样使用UTF-16LE编码,同时建议使用参数列表而非shell=True,避免shell解析时的编码问题:

# 假设已从cmd_output中提取到正确的Wi-Fi名称,比如"İnternetim"
profile_name = "İnternetim"

try:
    # 使用参数列表传递命令,避免shell解析编码问题
    result_bytes = subprocess.check_output(
        ['netsh', 'wlan', 'show', 'profile', profile_name, 'key=clear']
    )
    result = result_bytes.decode('utf-16le')
    print(result)
except subprocess.CalledProcessError as e:
    print(f"处理配置文件 {profile_name} 时出错: {e}")

关键说明

  • 去掉errors='ignore':该参数会掩盖解码错误,导致字符丢失,应使用默认的errors='strict'来及时发现编码问题
  • UTF-16LE是Windows命令行工具的通用输出编码:大部分Windows原生命令(如netsh、dir等)都会采用该编码输出Unicode内容
  • 使用参数列表替代shell=True:避免shell对特殊字符(如非ASCII字符)的解析干扰,提升命令执行的可靠性

内容的提问来源于stack exchange,提问作者Alperen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:51:20