我正在使用 subprocess.check_output
从 Python 运行命令 netsh wlan show faces
并将其收集在变量中。
a = subprocess.check_output(["netsh","wlan","show","interfaces"])
它给我的输出为:
>>> print a
>>> \r\nThere is 1 interface on the system: \r\n\r\n Name : Wireless Network Connection\r\n Description : Ralink RT3290 802.11bgn Wi-Fi Adapter\r\n GUID : 77cbe2d6-1a1e-41e7-be0a-3f18689c9ceb\r\n Physical address : c0:38:96:92:b7:1d\r\n State : connected\r\n SSID : PenguinWiFi\r\n BSSID : 6c:72:20:d2:f9:21\r\n Network type : Infrastructure\r\n Radio type : 802.11n\r\n Authentication : WPA2-Personal\r\n Cipher : CCMP\r\n Connection mode : Auto Connect\r\n Channel : 11\r\n Receive rate (Mbps) : 72\r\n Transmit rate (Mbps) : 72\r\n Signal : 100% \r\n Profile : PenguinWiFi \r\n\r\n Hosted network status : Not available\r\n\r\n'
我想从此输出中获取 wlan 的状态:“已连接”
或 “未连接”
。
为此,我想将上面的字符串转换为字典,并希望使用 "state"
作为键,以便我可以从键中获取值并决定是否 wlan
已连接或未连接。
但是当我将其转换为字典时,它会给出如下错误:
>>> a_dict = dict(a)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a_dict = dict(a)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
我不明白真正的问题是什么,是字符串问题还是其他问题?
最佳答案
I am not getting what is the real problem, its with the string or something else?
您不能只是将字符串转换为字典,即使该字符串读起来就像人类一样。
您必须解析该字符串并从中提取(键,值)对。
关键是例如“物理地址”和值“c0:38:96:92:b7:1d”
netsh 有一个计算机可读的 XML 输出
The Netsh commands for the Windows Filtering Platform (WFP) enable you The tool then exports the collected data into an XML file that you can examine for clues to the cause of the problem.
为什么不使用 XML output而不是脆弱的黑客可能会在最微小的控制台输出格式更改时停止工作?
netsh wlan export profile folder="PATH_TO_FOLDER" name=PROFILENAME
这应该为您提供一个计算机可读的文件,可以使用 Python numerous XML tools 轻松遍历。 .
从对列表中形成字典
ValueError: dictionary update sequence element #0 has length 1; 2 is required
这是因为 dict
需要一个(键,值)对列表来形成字典。 (key, value) 的长度为 2(它是一对)
例如
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}
关于python - 将 subprocess.check_output() 的输出转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34460199/