python-3.x 使用plistlib访问system_profiler plist项

j9per5c4  于 2022-12-27  发布在  Python
关注(0)|答案(1)|浏览(74)

我正在尝试访问生成的plist中第一个_items数组的serial_number键:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>_SPCommandLineArguments</key>
        <array>
            <string>/usr/sbin/system_profiler</string>
            <string>-nospawn</string>
            <string>-xml</string>
            <string>SPHardwareDataType</string>
            <string>-detailLevel</string>
            <string>full</string>
        </array>
        <key>_SPCompletionInterval</key>
        <real>0.15617406368255615</real>
        <key>_SPResponseTime</key>
        <real>0.18982398509979248</real>
        <key>_dataType</key>
        <string>SPHardwareDataType</string>
        <key>_detailLevel</key>
        <string>-2</string>
        <key>_items</key>
        <array>
            <dict>
                <key>serial_number</key>
                <string>C0**</string>
            </dict>
        </array>
    </dict>
</array>
</plist>

下面是Python代码:

def get_serial_number():
        import plistlib
        cmd = ['system_profiler', 'SPHardwareDataType', '-xml']
        plist = subprocess.check_output(cmd)
        with open('hardware.plist', 'wb') as fp:
            plistlib.dump(plist, fp)
        with open('hardware.plist', 'rb') as fp:
            pl = plistlib.load(fp, fmt=None, dict_type=dict)
            serial = pl[0]['_items'][0]['serial_number']
        return serial

我收到的错误是:'int' object is not subscriptable.我假设这是因为我试图访问第9行上的plist的键的方式,但我无法弄清楚。
任何帮助将不胜感激!

sg3maiej

sg3maiej1#

这是一个非常有趣的工作!我认为您希望它从system_profilerplist获取序列号

import plistlib
import subprocess

cmd = ['system_profiler', 'SPHardwareDataType', '-xml']
plist = subprocess.check_output(cmd)

pl = plistlib.loads(plist, fmt=None, dict_type=dict)
print(pl[0]['_items'][0]['serial_number'])

您也可以不使用plistlib执行此操作,如下所示:

import subprocess

cmd = ['system_profiler', 'SPHardwareDataType']
profile = subprocess.check_output(cmd).decode('utf-8')
for line in profile.splitlines():
   if 'Serial Number' in line:
       serial = line.split()[-1]

相关问题