Python 编码问题,无法识别网络适配器



这是我的一段python代码草稿。

import os
print 'netsh interface ip set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1'

到目前为止,一切都很好,适配器包含在我的驱动程序中。

现在当我运行它时(作为管理员(

os.system('netsh interface ipv4 set address name="' + adapter + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')

它会触发此错误:

La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte.

这意味着命令的语法不正确。

我试过os.system('netsh interface ipv4 set address name="' + adapter.encode('ascii','ignore') + '" static '+ staticaddr +' 255.255.255.0 192.168.1.1')

现在发生这种异常:

'ascii' codec can't decode byte 0x82 in position 11: ordinal not in range(128)

问题到底在哪里?

我的网络适配器的名称是 :Connexion réseau sans fil

adapter.encode('ascii','ignore')会引发UnicodeDecodeErroradapter因为是一个非ASCII str。为了对它进行编码(即从Unicode转换为str(,Python首先尝试对其进行解码(即从str转换为unicode(并失败(adapter是非ascii(。

完全切换到 unicode:

print (u'netsh interface ip set address name="' + adapter.decode('latin1') + u'" static '+ staticaddr.decode('ascii') + u' 255.255.255.0 192.168.1.1').encode('latin1')

我最终遇到了类似的问题。 我有一个脚本,列出了所有以前连接的Wi-Fi网络及其密码。一个特定的网络("Gestão TI"(让我头疼,因为当我运行命令时,名称返回为"GestÆo TI",并且由于名称已更改,因此以下命令无法运行。 我尝试了几种不同的编码,例如UTF-8,Latin-1等,但没有成功。 我的一位朋友向我指出,也许问题出在导出名称时的netsh编码上。由于netsh相当古老,他建议我尝试使用旧的拉丁编码(CP850(,它终于奏效了......

最新更新