在 Python 中处理 subprocess.check_output 中的土耳其语/非 ascii 字符

问题描述 投票:0回答:1

在 Python 中使用

subprocess.check_output
方法时,我遇到处理土耳其语字符的问题。我的目标是检索 Windows 系统上的 Wi-Fi 配置文件名称,其中可能包含土耳其字符,例如“ı”、“ü”、“ş”。但是,当使用
subprocess.check_output
并将编码设置为“utf-8”、“ISO-8859-9”或“windows-1254”时,土耳其语字符无法正确表示。

这是我的代码片段:

import subprocess

try:
    command_output = subprocess.check_output("netsh wlan show profile", shell=True, encoding='utf-8', errors='ignore')
    # Also tried with 'ISO-8859-9' and 'windows-1254'
except subprocess.CalledProcessError as e:
    print(f"Command error: {e}")
    command_output = ""

此问题出现在 Wi-Fi 名称包含土耳其语字符时,例如“INTERNETIM”(“我的互联网”)或“AĞIM”(“我的网络”)。这些字符要么被省略,要么被错误的字符替换,例如“互联网

我运行了我的代码,在使用土耳其语配置文件名称的 wifi 上遇到了此错误。

配置文件错误 nternetim:命令 'netsh wlan show profile "nternetim" key=clear' 返回非零退出状态 1。 Profil işlenirken hata AIM:命令 'netsh wlan show profile "AIM" key=clear' 返回非零退出状态 1。

从代码输出中可以看出,字母丢失了。

还尝试过“ISO-8859-9”和“windows-1254”。

python python-3.x character-encoding subprocess ssid
1个回答
0
投票

因为无法保证任何 SSID 使用哪种字符编码,所以您只能猜测。取出

encoding
关键字,您将收到字节,然后您可以根据您能想到的任何启发式方法连续尝试解码这些字节。

import subprocess

try:
    command_output = subprocess.check_output("netsh wlan show profile", shell=True)
    # Also tried with 'ISO-8859-9' and 'windows-1254'
except subprocess.CalledProcessError as e:
    print(f"Command error: {e}")
    command_output = ""

for encoding in ('utf-8', 'ISO-8859-9', 'windows-1254'):
    try:
        command_output = command_output.decode(encoding)
        break
    except UnicodeDecodingError:
        pass
    else:
        raise UnicodeDecodingError("Could not find a valid encoding for '%r'" % command_output)

UTF-8 非常强大,因为它会拒绝大多数无效 UTF-8 的字符串。其他传统的 8 位编码通常会很乐意接受几乎任何字符串而不会出现错误,但如果您猜测不正确,则会导致虚假数据。

您可能想要添加更多编码,和/或看看是否可以对字符串执行某种频率分析来建立最可能的编码。 (

chardet
图书馆为此提供了一些设施。)

© www.soinside.com 2019 - 2024. All rights reserved.