从命令输出中获取特定数据

2024-04-26 17:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我将从OSX命令输出中获取特定数据,示例-

enter image description here

我的代码:

import os
import json
import plistlib
import subprocess
import datetime

def _LogicalDrive():

    tmp_l = []

    output = subprocess.Popen(
        "diskutil info -all", shell=True,
        stdout=subprocess.PIPE).stdout.read().splitlines()

    for x in output:
        if 'Device Identifier' in x:
            tmp_dict['Identifier'] = x.split(' ')[-1].strip()
        tmp_l.append(tmp_dict)    
    return tmp_l
print _LogicalDrive()

我想从特定密钥获取数据,如“设备/媒体名称”或其他。你知道吗


Tags: 数据代码inimport命令示例outputos
2条回答

我认为您正在尝试解析命令输出并对其进行分析。你把它分成几行是好事。也许,在每一行中,用“:\s+”模式将其进一步拆分,并将冒号的左部分存储为键,右部分存储为值(也许在字典中)。您可以使用该字典以键(冒号的左部分)进行查询以获取值。你知道吗

如果按“:\s+”存储拆分模式,则可以重复使用它;或者在必须指定键的位置再添加一个参数。你知道吗

您可以迭代输出并在:上拆分每一行,将左部分作为键,右部分作为值。你知道吗

def _LogicalDrive():

    tmp_l = []

    output = subprocess.Popen(
        "diskutil info -all", shell=True,
        stdout=subprocess.PIPE).stdout.read()

    for x in output.splitlines():
        try:
            key, value = [c.strip() for c in x.split(':') if ':' in x]
        except ValueError:
            continue
        if 'Device Identifier' in x:
            tmp_dict['Identifier'] = value
        tmp_l.append(tmp_dict)

    return tmp_l

相关问题 更多 >