2015-05-02 188 views
0

我想要做的是創建兩個字段的字典(UUID的路徑)和Ubuntu的命令行填補他們輸出Python的字典創建類型錯誤

from subprocess import Popen, PIPE 

Devices = [] 


def UUID(): 
    blkid = Popen(['sudo', 'blkid'], stdout=PIPE) 
    sed = Popen(['sed', 's/^.*UUID="/UUID="/'], stdin=blkid.stdout, stdout=PIPE) 
    cut = Popen(['cut', '-d', '"', '-f', '2'], stdin=sed.stdout, stdout=PIPE) 
    end_of_pipe = cut.stdout 
    Devices = [{'uuid': uuid, 'path': None} for uuid in end_of_pipe] 
    return Devices 


def Path(Devices): 
    blkid = Popen(['sudo', 'blkid'], stdout=PIPE) 
    cut = Popen(['cut', '-d', ':', '-f', '1'], stdin=blkid.stdout, stdout=PIPE) 
    end_of_pipe = cut.stdout 
    for path in end_of_pipe: 
     Devices['path'] = path 
    return Devices 

Devices = UUID() 
Path(Devices) 
print Devices 

返回錯誤:

Traceback (most recent call last): 
    File "2.py", line 24, in <module> 
    Path(Devices) 
    File "2.py", line 20, in Path 
    Devices['path'] = path 
TypeError: list indices must be integers, not str 
+0

什麼讓你對這個錯誤感到困惑?設備是一個列表,你不能用字符串索引列表。 –

回答

1

Devicesdictlist對象,而不是dict對象本身。您必須先確定要訪問的索引,然後訪問該對象的path鍵。一個例子是:

Device[0]['path'] = 'some/path' 

在你的情況,如果end_of_pipe相同的順序持有路徑,Devices你可以這樣做:

for path, device in zip(end_of_pipe, Devices): 
    device['path'] = path 
0

Python是能夠分析文本。您不需要使用外部工具,如sed剪切來做到這一點。

import re 
from subprocess import Popen, Pipe 

pattern = re.compile(r'^(?P<path>[^:]+).*UUID="(?P<uuid>[^"]+)') 
devices = [] 
blkid = Popen(['sudo', 'blkid'], stdout=PIPE) 
for line in f: 
    match_object = re.match(pattern, line) 
    if match_object: 
     devices.append(match_object.groupdict()) 

在這一點上,設備將包含字典的列表,每個字典包含兩個鍵:路徑UUID。此解決方案還有另一個優點:您只需撥打blkid一次。