使用plistlib访问system_profiler plist项



我试图访问生成的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的键的方式,但我无法弄清楚。

任何帮助都将非常感激!

算起来真有趣!我想你希望这个从system_profiler中获得序列号plist

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]

相关内容

  • 没有找到相关文章

最新更新