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

如何解决WiFi名称带重音符号时Python解码netsh输出报错问题

解决方法

报错原因

Windows西语系统的命令行默认输出编码为cp1252(latin-1),Python默认使用utf-8解码,编码不匹配就会触发该错误。

方案1:指定正确编码解码(无需移除重音)

直接在所有decode()方法中指定编码为cp1252即可,不需要修改字符内容,能完整保留西语重音字符。

方案2:移除重音符号(可选)

如果需要统一去除所有重音,可以配合你已导入的unicodedata模块做字符归一化处理,示例处理逻辑:

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])

修正后的完整代码

同时修复了你原代码中两处遗漏参数的问题:

import subprocess
import re
import unicodedata

# 指定编码为西语系统默认的cp1252
command_output = subprocess.run(['netsh','wlan','show','profiles'], capture_output=True).stdout.decode('cp1252')
profile_names = re.findall("Perfil de todos los usuarios     : (.*)\r", command_output)
wifi_list = []

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])

if len(profile_names) != 0:
    for red in profile_names:
        wifi_profile = {}
        profile_info = subprocess.run(['netsh','wlan','show','profiles', red], capture_output=True).stdout.decode('cp1252')
        # 如果需要去重音可以取消注释下一行
        # profile_info = remove_accents(profile_info)

        if re.search("Clave de seguridad                         : Ausente", profile_info):
            continue
        else:
            wifi_profile["ssid"] = red
            # 补全capture_output参数和解码逻辑
            profile_info_pass = subprocess.run(["netsh","wlan","show","profile", red ,"key=clear"], capture_output=True).stdout.decode('cp1252')
            # 补全re.search的搜索对象参数
            password = re.search("Contenido de la clave  : (.*)\r", profile_info_pass)

            if password == None:
                wifi_profile["password"] = None
            else:
                wifi_profile["password"] = password[1]
            wifi_list.append(wifi_profile)

for x in range(len(wifi_list)):
    print(wifi_list[x])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:54:04