2017-04-05 181 views
0

具体的数据我会从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() 

我想从具体的关键数据,如“设备/媒体名称”或其他。

+0

什么不在你的代码中工作?你得到的输出是什么?什么是预期呢? –

+0

输出图片是“https://i.stack.imgur.com/ZNM1b.png” – DKmolko

+0

我的代码会得到所有不是我想要的东西 – DKmolko

回答

0

我想你正试图解析命令输出并分析它。它很好,你将它分解成单独的行。也许,在每一行中用“:\ s +”模式进一步分割并将冒号的左侧部分存储为键值和右侧部分(可能在字典中)。您可以使用该字典用键(冒号的左侧部分)查询以获取该值。

如果通过“:\ s +”存储分割模式,则可以重新使用它;也许在需要指定密钥的地方再增加一个参数。

+0

您可以提供示例代码吗?我对Python的格式数据很差 – DKmolko

0

您可以迭代输出,并将每行分割为:,其中左侧部分为键,右侧为值。

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 
+0

有一些错误:“key,value = [c.strip()for x.split(':')]”,ValueError:需要多个值才能解包 – DKmolko

+0

更新了我的答案。没有照顾空白线条。 –

+0

对不起,但“ValueError:需要超过0个值才能解包”出现..... – DKmolko