我想使用python3将“ command> systeminfo”的输出解析为json

时间:2018-09-21 10:24:42

标签: json python-3.x parsing

我想将命令systeminfo的输出转换为json。 但是我只需要一些特定的信息。 而且我必须避免第一行(命令行),它并不总是在第一行。

如何通过python3实现呢?

我将输出保存到.txt文件中。 下面是输出的一部分。

C:\Users\user\Desktop>systeminfo
Host Name:                 COMPUTERHOPE
OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.10586 N/A Build 10586
OS Manufacturer:           Microsoft Corporation
OS Configuration:          Standalone Workstation
OS Build Type:             Multiprocessor Free
Registered Owner:          Computerhope
Registered Organization:   Computer Hope
Product ID:                00000-00000-00000-AAAAA
Original Install Date:     12/17/2015, 7:09:50 PM
System Boot Time:          3/28/2016, 6:57:39 AM
System Manufacturer:       Dell Inc.
System Model:              XPS 8300
System Type:               x64-based PC
Processor(s):              1 Processor(s) Installed.
                           [01]: Intel64 Family 6 Model 42 Stepping 7 Genuine Intel ~3401

我希望它像这样。

{
    "Host Name": "COMPUTERHOPE",
    "OS Name": "Microsoft Windows 10 Pro",
    "OS Version": "10.0.10586 N/A Build 10586",
    "Original Install Date": 
    {
     "Date": "12/17/2015",
     "Time": "7:09:50 PM",
    }
}

1 个答案:

答案 0 :(得分:2)

import json, subprocess

def get_systeminfo():
    # Command to run.
    command = ['systeminfo']

    # Run the commands and get the stdout.
    with subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE) as p:
        stdout, _ = p.communicate()

    return stdout


def dic_from_systeminfo(stdout):
    # Dic to store all info.
    dic = {}

    # Previous key name saved to reuse for dic values.
    prevkey = ''

    # Loop through each line of stdout and split by colon.
    for line in stdout.splitlines():
        key, sep, value = line.partition(':')

        if sep == ':':
            value = value.strip()

            if not key.startswith(' '):
                # Assign these keys with values of type dic.
                if key in ('Original Install Date', 'System Boot Time'):
                    value = {k: v.strip() for k, v in zip(('Date', 'Time'), value.split(','))}
                elif key in ('Processor(s)', 'Hotfix(s)', 'Network Card(s)'):
                    value = dict()

                # Add to dic and save key name.
                dic[key] = value
                prevkey = key
            else:
                # Remove [] characters and then add key and value to the value type dic.
                key = key.strip().replace('[', '').replace(']', '')

                if prevkey and isinstance(dic[prevkey], dict):
                    dic[prevkey][key] = value
                else:
                    print('Warning:', 'dic[' + prevkey + '] is not a dict value.')

    return dic

# Run Systeminfo and get stdout.
stdout = get_systeminfo()

# Get dic from stdout (or read file content).
dic = dic_from_systeminfo(stdout)

# Write the dic to file.
if dic:
    with open('systeminfo.json', 'w', encoding='utf-8') as w:
        json.dump(dic, w, indent=4)

脚本执行命令systeminfo并获取标准输出。

for循环中逐行处理标准输出,然后 使用str.partition方法将其分为键和值。

如果键名不以空格开头,则它是根键。 如果它与特殊键名之一匹配,它将设置为 字典类型的值,否则将使用当前值进行设置。 密钥名称将保存到prevkey,以便在else条件为 触发后,prevkey可以用作根密钥,并且 键和值将设置为该根键。

在else条件下,从键中删除方括号, 尽管可以将其视为可选首选项。

如果dic是东西,那么它将被写入systeminfo.json

如果您只想要某些键,则可以将感兴趣的键保存到 单独的字典并将其写入文件。


作为读取现有文件的主要代码,请使用:

stdout = ''

# Read from existing file.
with open('sysinfo.txt') as r:
    stdout = r.read()

# Get dic from stdout (or read file content).
dic = dic_from_systeminfo(stdout)

# Write the dic to file.
if dic:
    with open('systeminfo.json', 'w', encoding='utf-8') as w:
        json.dump(dic, w, indent=4)