简体   繁体   English

使用 Python 解析 Windows 中的命令行 Output

[英]Parsing Command Line Output in Windows with Python

I essentially want to get some values from a command like 'ipconfig', but when I print the output of the command I get alot of newline characters and spaces.我本质上想从像“ipconfig”这样的命令中获取一些值,但是当我打印命令的 output 时,我得到了很多换行符和空格。

Code I've Tried:我试过的代码:

>>> 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...

I'm not sure of the best way to parse this data into some sort of table with keys and values我不确定将这些数据解析为某种带有键和值的表的最佳方法

And when trying to use code from this answer to this question here , all I could get was this error:当尝试在这里使用这个问题的答案中的代码时,我能得到的只是这个错误:

>>> 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'

Example of what I'm looking for:我正在寻找的示例:

"Link-local IPv6 Address": "my ipv6 addr" “链接本地 IPv6 地址”:“我的 ipv6 地址”

"Subnet Mask": "my subnet mask" “子网掩码”:“我的子网掩码”

(Using python 3) (使用 python 3)

We get the output, decode it so it's a str , then iterate over its lines.我们得到 output,将其解码为str ,然后遍历其行。

We'll store each separate adapter as a dict in a dict named adapters .我们将每个单独的适配器作为dict存储在名为adaptersdict中。

In the output, preceding the details of each adapter is a line starting with "Ethernet adapter " .在 output 中,每个适配器的详细信息之前是一行以"Ethernet adapter "开头的行。 We get the adapter's name by splicing the line from after the string "Ethernet adapter " to just before the ":" which is at index -1 .我们通过将字符串"Ethernet adapter "之后的行拼接到索引-1处的":"之前的行来获取适配器的名称。

After that, it is assumed any line with ": " in it has details about the current adapter.之后,假设任何带有": "的行都包含有关当前适配器的详细信息。 So we split the line at ": " , clean it up a bit, and use them as key/value pairs for our current_adapter dict which we created earlier.因此,我们在": "处拆分行,稍微清理一下,并将它们用作我们之前创建的current_adapter dict的键/值对。

import subprocess

adapters = {}
output = subprocess.check_output("ipconfig").decode()

for line in output.splitlines():
    term = "Ethernet adapter "
    if line.startswith(term):
        adapter_name = line[len(term):-1]
        adapters[adapter_name] = {}
        current_adapter = adapters[adapter_name]
        continue

    split_at = " : "
    if split_at in line:
        key, value = line.split(split_at)
        key = key.replace(" .", "").strip()
        current_adapter[key] = value



for adapter_name, adapter in adapters.items():
    print(f"{adapter_name}:")
    for key, value in adapter.items():
        print(f"    '{key}' = '{value}'")
    print()

Output: Output:

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' = ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM