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
相关产品推荐
相关产品推荐

