Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从命令输出中获取特定数据_Python - Fatal编程技术网

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

Python 从命令输出中获取特定数据,python,Python,我将从OSX命令输出中获取特定数据,示例- 我的代码: 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).stdou

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

我的代码:

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()

我想从特定键(如“设备/媒体名称”或其他键)获取数据。

我想您正在尝试解析命令输出并对其进行分析。你把它分成几行是件好事。也许,在每一行中,使用“:\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

还有哪些代码不起作用?您得到的输出是什么?预期结果是什么?输出图片是“我的代码将获得所有项目,而不是我想要的。您可以给出示例代码吗?我对python的格式数据很差。某些内容是错误的:“key,value=[c.strip(),for c in x.split(':')]”),ValueError:需要超过1个值才能解压更新我的答案。没有处理空行。很抱歉,出现了“ValueError:需要0个以上的值才能解包”……我可能没有预期的输出,所以只使用常规的try Exception块。我用命令输出的前5行尝试了您的代码,没有错误,但函数输出如下:[{Identifier':'disk0'},{'Identifier':'},{'Identifier':'},{'Identifier':'''},{'Identifier':'''}],就像我之前所说的,它将匹配所有行,而不是特定于函数的哪些行