Python 字典创建类型错误

Python Dictionary Creation TypeError

我想做的是创建一个包含两个字段的字典(uuid 一个路径)并用 ubuntu 命令行输出

填充它们
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

Deviceslistdict 个对象,而不是 dict 个对象本身。你得先弄清楚你要访问哪个索引,然后访问对象的path键。一个例子是:

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

在您的情况下,if end_of_pipeDevices 相同的顺序 保存路径,您可以这样做:

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

Python 能够解析文本。您不需要使用 sedcut 等外部工具来执行此操作。

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

此时,devices会包含一个字典列表,每个字典包含两个key:path uuid。此解决方案还有另一个优点:您只需调用 blkid 一次。