2017-04-05 179 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