我正在尝试访问生成的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的键的方式,但我无法弄清楚。
任何帮助将不胜感激!
1条答案
按热度按时间sg3maiej1#
这是一个非常有趣的工作!我认为您希望它从system_profiler
plist
获取序列号您也可以不使用
plistlib
执行此操作,如下所示: