用Python解析Windows中的命令行输出
我基本上想从命令“ipconfig”中获取一些值,但是当 我打印命令的输出,得到很多换行符和空格 我尝试过的代码:用Python解析Windows中的命令行输出,python,python-3.x,parsing,Python,Python 3.x,Parsing,我基本上想从命令“ipconfig”中获取一些值,但是当 我打印命令的输出,得到很多换行符和空格 我尝试过的代码: >>> import subprocess >>> output = subprocess.getstatusoutput("ipconfig") >>> print(output) (0, '\x0c\nWindows IP Configuration\n\n\nEthernet adapter Ethernet 2:\n\n
>>> import subprocess
>>> output = subprocess.getstatusoutput("ipconfig")
>>> print(output)
(0, '\x0c\nWindows IP Configuration\n\n\nEthernet adapter Ethernet 2:\n\n Media State . . . . . . . . . . . : Media disconnected\n Connection-specific DNS Suffix . : \n\nEthernet adapter Npcap Loopback Adapter:\n\n
Connection-specific DNS Suffix . : \n Link-local IPv6 Address . . . . . : ~e~~::7dab:~~7f:e56f:1131%9\n Autoconfiguration IPv4 Address. . : 169.~~4.1~.49\n
Subnet Mask . . . . . . . . . . . : 255.255.0.0\n Default Gateway . . . . . . . . . : \n\nEthernet adapter VirtualBox Host-Only Network:\n\n Connection-specific DNS Suffix . : \n
Link-local IPv6 Address . . . . . : fe80::7~~c:69aa:~~aa:~~14~10\n IPv4 Address. . . . . . . . . . . : 192.168.~~.~\n Subnet Mask . . . . . . . . . . . : 255.~~~.255.0\n Default Gateway . . . . : etc...
我不确定将这些数据解析成某种带有键和值的表的最佳方法
当我试图使用这个问题答案中的代码时,我只能得到以下错误:
>>> import subprocess
>>> output = subprocess.check_output("ipconfig", shell=True)
>>> result = {}
>>> for row in output.split('\n'):
... if ': ' in row:
... key, value = row.split(': ')
... result[key.strip(' .')] = value.strip()
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> print(result)
{}
>>> print(result['A (Host) Record'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'A (Host) Record'
导入子流程
>>>输出=子进程。检查输出(“ipconfig”,shell=True)
>>>结果={}
>>>对于output.split('\n')中的行:
... 如果行中有“:”:
... 键,值=行。拆分(“:”)
... 结果[key.strip('.')]=value.strip()
...
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:需要类似字节的对象,而不是“str”
>>>打印(结果)
{}
>>>打印(结果['A(主机)记录'])
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
KeyError:“A(主机)记录”
我正在寻找的示例:
“链接本地IPv6地址”:“我的IPv6地址”
“子网掩码”:“我的子网掩码”
(使用python 3)我们得到输出,对其进行解码,使其成为一个
str
,然后对其行进行迭代
我们将把每个单独的适配器作为dict
存储在名为adapters
的dict
中
在输出中,每个适配器的详细信息前面是一行,以“Ethernet adapter”开头。我们通过将字符串“Ethernet adapter”
后面的行拼接到索引-1
处的“
前面的行来获得适配器的名称
在此之后,假定其中包含“:”
的任何行都包含有关当前适配器的详细信息。因此,我们在“:”
处拆分行,稍微清理一下,并将它们用作我们先前创建的当前\u适配器
dict
的键/值对
导入子流程
适配器={}
输出=子进程。检查输出(“ipconfig”).decode()
对于输出中的行。拆分行():
term=“以太网适配器”
如果行开始使用(术语):
适配器名称=行[len(术语):-1]
适配器[适配器名称]={}
当前适配器=适配器[适配器名称]
持续
split_at=“:”
如果在直线上拆分_:
键,值=行分割(分割处)
key=key.replace(“.”,“”)。strip()
当前适配器[键]=值
对于适配器名称,适配器中的适配器。项()
打印(f“{adapter_name}:”)
对于键,adapter.items()中的值:
打印(f“{key}”=“{value}”)
打印()
输出:
Ethernet:
'Connection-specific DNS Suffix' = ''
'Link-local IPv6 Address' = 'fe80::...'
'IPv4 Address.' = '192.168.255.255'
'Subnet Mask' = '255.255.255.255'
'Default Gateway' = '192.168.255.255'
VMware Network Adapter VMnet1:
'Connection-specific DNS Suffix' = ''
'Link-local IPv6 Address' = 'fe80::...'
'IPv4 Address.' = '192.168.255.255'
'Subnet Mask' = '255.255.255.255'
'Default Gateway' = ''
VMware Network Adapter VMnet8:
'Connection-specific DNS Suffix' = ''
'Link-local IPv6 Address' = 'fe80::...'
'IPv4 Address.' = '192.168.255.255'
'Subnet Mask' = '255.255.255.255'
'Default Gateway' = ''
你想得到什么具体信息?可能有一个API来获取它,这将完全避免这个问题。另一个选项是
wmic
,它可以输出XML:@wjandrea我不想要任何特定的信息,否则我将使用一个模块。我只想将数据解析为字典类型的结构。我将尝试使用wmic选项,因为您的最终目标是学习如何解析输出?值得注意的是,如果您有无线适配器或隧道适配器,或者如果您使用ipconfig/all
,这将不起作用。但是修改它不会花费太长时间,所以它会这么做。@GordanAitchJay非常感谢我对你的代码做了一点修改,它工作得非常完美!