我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用plistlib.loads()。
def test_int(self): for pl in [0, 2**8-1, 2**8, 2**16-1, 2**16, 2**32-1, 2**32, 2**63-1, 2**64-1, 1, -2**63]: for fmt in ALL_FORMATS: with self.subTest(pl=pl, fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertIsInstance(pl2, int) self.assertEqual(pl, pl2) data2 = plistlib.dumps(pl2, fmt=fmt) self.assertEqual(data, data2) for fmt in ALL_FORMATS: for pl in (2 ** 64 + 1, 2 ** 127-1, -2**64, -2 ** 127): with self.subTest(pl=pl, fmt=fmt): self.assertRaises(OverflowError, plistlib.dumps, pl, fmt=fmt)
def test_keysort(self): pl = collections.OrderedDict() pl['b'] = 1 pl['a'] = 2 pl['c'] = 3 for fmt in ALL_FORMATS: for sort_keys in (False, True): with self.subTest(fmt=fmt, sort_keys=sort_keys): data = plistlib.dumps(pl, fmt=fmt, sort_keys=sort_keys) pl2 = plistlib.loads(data, dict_type=collections.OrderedDict) self.assertEqual(dict(pl), dict(pl2)) if sort_keys: self.assertEqual(list(pl2.keys()), ['a', 'b', 'c']) else: self.assertEqual(list(pl2.keys()), ['b', 'a', 'c'])
def test_skipkeys(self): pl = { 42: 'aNumber', 'snake': 'aWord', } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps( pl, fmt=fmt, skipkeys=True, sort_keys=False) pl2 = plistlib.loads(data) self.assertEqual(pl2, {'snake': 'aWord'}) fp = BytesIO() plistlib.dump( pl, fp, fmt=fmt, skipkeys=True, sort_keys=False) data = fp.getvalue() pl2 = plistlib.loads(fp.getvalue()) self.assertEqual(pl2, {'snake': 'aWord'})
def test_tuple_members(self): pl = { 'first': (1, 2), 'second': (1, 2), 'third': (3, 4), } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertEqual(pl2, { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], }) self.assertIsNot(pl2['first'], pl2['second'])
def test_list_members(self): pl = { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], } for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): data = plistlib.dumps(pl, fmt=fmt) pl2 = plistlib.loads(data) self.assertEqual(pl2, { 'first': [1, 2], 'second': [1, 2], 'third': [3, 4], }) self.assertIsNot(pl2['first'], pl2['second'])
def test_dataobject_deprecated(self): in_data = { 'key': plistlib.Data(b'hello') } out_data = { 'key': b'hello' } buf = plistlib.dumps(in_data) cur = plistlib.loads(buf) self.assertEqual(cur, out_data) self.assertNotEqual(cur, in_data) cur = plistlib.loads(buf, use_builtin_types=False) self.assertNotEqual(cur, out_data) self.assertEqual(cur, in_data) with self.assertWarns(DeprecationWarning): cur = plistlib.readPlistFromBytes(buf) self.assertNotEqual(cur, out_data) self.assertEqual(cur, in_data)
def get_catalog(catalog_url): """Obtaines the Apple software catalog as a dict""" try: catalog_request = urlopen(catalog_url) except (IOError, URLError, HTTPError): raise CampiesError( 'Unable to download catalog URL {catalog_url}'.format( catalog_url=catalog_url ) ) catalog_xml = catalog_request.read() try: catalog = loads_plist(catalog_xml) except xml.parsers.expat.ExpatError: raise CampiesError( 'Unable to parse catalog XML to obtain software details' ) return catalog
def finish_authentication(self, username, password): """Finish authentication process. A username (generated by new_credentials) and the PIN code shown on screen must be provided. """ # Step 1 self.srp.step1(username, password) data = yield from self._send_plist( 'step1', method='pin', user=username) resp = plistlib.loads(data) # Step 2 pub_key, key_proof = self.srp.step2(resp['pk'], resp['salt']) yield from self._send_plist( 'step2', pk=binascii.unhexlify(pub_key), proof=binascii.unhexlify(key_proof)) # Step 3 epk, tag = self.srp.step3() yield from self._send_plist('step3', epk=epk, authTag=tag) return True
def do_POST(self): """Called when a new event has been received""" # make sure this is what we expect if self.path != '/event': raise RuntimeError('Unexpected path when parsing event: {0}'.format(self.path)) # validate our content type content_type = self.headers.get('content-type', None) if content_type != 'text/x-apple-plist+xml': raise RuntimeError('Unexpected Content-Type when parsing event: {0}'.format(content_type)) # and the body length content_length = int(self.headers.get('content-length', 0)) if content_length == 0: raise RuntimeError('Received an event with a zero length body.') # parse XML plist self.event = plist_loads(self.rfile.read(content_length))
def plist(self): if self.__plist: return self.__plist pattern = re.compile(r'Payload/[^/]*.app/Info.plist') for path in self.zip.namelist(): m = pattern.match(path) if m is not None: # print(m) data = self.zip.read(m.group()) self.__plist = plistlib.loads(data) return self.__plist
def readPlist(pathOrFile): """Raises NotBinaryPlistException, InvalidPlistException""" didOpen = False result = None if isinstance(pathOrFile, (bytes, unicode)): pathOrFile = open(pathOrFile, 'rb') didOpen = True try: reader = PlistReader(pathOrFile) result = reader.parse() except NotBinaryPlistException as e: try: pathOrFile.seek(0) result = None if hasattr(plistlib, 'loads'): contents = None if isinstance(pathOrFile, (bytes, unicode)): with open(pathOrFile, 'rb') as f: contents = f.read() else: contents = pathOrFile.read() result = plistlib.loads(contents) else: result = plistlib.readPlist(pathOrFile) result = wrapDataObject(result, for_binary=True) except Exception as e: raise InvalidPlistException(e) finally: if didOpen: pathOrFile.close() return result
def get_bundle_identifier(file_path): for root, dirs, files in os.walk(file_path): for file in files: if file == 'Info.plist': with open(os.path.join(root, file), 'rb') as plist_file: plist = plistlib.loads(plist_file.read()) try: return plist['CFBundleIdentifier'], plist['CFBundleShortVersionString'], plist['CFBundleVersion'] except: traceback.print_exc() print(plist) return raise Exception("can not find Info.plist")
def data_received(self, data): self._buf += data while len(self._buf) > 4: length = struct.unpack('I', self._buf[:4])[0] if len(self._buf) < length: return ver, req, tag = struct.unpack('III', self._buf[4:16]) if ver != PLIST_VERSION: raise ProtocolError("Unsupported protocol version from usbmux stream") pldata = plistlib.loads(self._buf[16:length]) self.msg_received(pldata) self._buf = self._buf[length:]
def get_provisioning_profile_id(): try: profile = subprocess.check_output(['security', 'cms', '-D', '-i', PROVISIONING_PROFILE], stderr=subprocess.STDOUT) plist = plistlib.loads(profile) return plist['UUID'] except subprocess.CalledProcessError: return None
def device_in_profile(udid): try: profile = subprocess.check_output(['security', 'cms', '-D', '-i', PROVISIONING_PROFILE]) plist = plistlib.loads(profile) return udid in plist['ProvisionedDevices'] except subprocess.CalledProcessError: return False
def test_bytes(self): pl = self._create() data = plistlib.dumps(pl) pl2 = plistlib.loads(data) self.assertNotIsInstance(pl, plistlib._InternalDict) self.assertEqual(dict(pl), dict(pl2)) data2 = plistlib.dumps(pl2) self.assertEqual(data, data2)
def test_indentation_array(self): data = [[[[[[[[{'test': b'aaaaaa'}]]]]]]]] self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_indentation_dict(self): data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': b'aaaaaa'}}}}}}}}} self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': b'aaaaaa'}]]]]]}]}} self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_appleformattingfromliteral(self): self.maxDiff = None for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): pl = self._create(fmt=fmt) pl2 = plistlib.loads(TESTDATA[fmt], fmt=fmt) self.assertEqual(dict(pl), dict(pl2), "generated data was not identical to Apple's output") pl2 = plistlib.loads(TESTDATA[fmt]) self.assertEqual(dict(pl), dict(pl2), "generated data was not identical to Apple's output")
def test_nondictroot(self): for fmt in ALL_FORMATS: with self.subTest(fmt=fmt): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.loads(plistlib.dumps(test1, fmt=fmt)) result2 = plistlib.loads(plistlib.dumps(test2, fmt=fmt)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
def test_invalidarray(self): for i in ["<key>key inside an array</key>", "<key>key inside an array2</key><real>3</real>", "<true/><key>key inside an array3</key>"]: self.assertRaises(ValueError, plistlib.loads, ("<plist><array>%s</array></plist>"%i).encode())
def test_invaliddict(self): for i in ["<key><true/>k</key><string>compound key</string>", "<key>single key</key>", "<string>missing key</string>", "<key>k1</key><string>v1</string><real>5.3</real>" "<key>k1</key><key>k2</key><string>double key</string>"]: self.assertRaises(ValueError, plistlib.loads, ("<plist><dict>%s</dict></plist>"%i).encode()) self.assertRaises(ValueError, plistlib.loads, ("<plist><array><dict>%s</dict></array></plist>"%i).encode())
def test_invalidinteger(self): self.assertRaises(ValueError, plistlib.loads, b"<plist><integer>not integer</integer></plist>")
def test_invalidreal(self): self.assertRaises(ValueError, plistlib.loads, b"<plist><integer>not real</integer></plist>")
def test_nonstandard_refs_size(self): # Issue #21538: Refs and offsets are 24-bit integers data = (b'bplist00' b'\xd1\x00\x00\x01\x00\x00\x02QaQb' b'\x00\x00\x08\x00\x00\x0f\x00\x00\x11' b'\x00\x00\x00\x00\x00\x00' b'\x03\x03' b'\x00\x00\x00\x00\x00\x00\x00\x03' b'\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x00\x00\x00\x00\x00\x00\x13') self.assertEqual(plistlib.loads(data), {'a': 'b'})
def get_model(): """Obtain's the user's Mac model""" # Obtain and parse the output of the system profiler command try: hardware_type_xml = run([ 'system_profiler', 'SPHardwareDataType', '-xml' ]) except CampiesSubprocessError: raise CampiesError( 'Unable to run the command required to obtain the model' ) try: hardware_type = loads_plist(hardware_type_xml) except xml.parsers.expat.ExpatError: raise CampiesError( 'Unable to parse hardware XML to obtain the model' ) # We now need to grab the machine model which is buried in the data # [{ # '_items': [ # { # '_name': 'hardware_overview', # 'machine_model': 'MacBookPro11,5', # 'machine_name': 'MacBook Pro', try: model = hardware_type[0]['_items'][0]['machine_model'] except IndexError: raise CampiesError( 'Unable to find model in the hardware XML' ) return model
def _wait_for_media_to_end(self, session): address = self._url(self.port, 'playback-info') play_state = const.PLAY_STATE_LOADING while True: info = None try: info = yield from session.get(address) data = yield from info.content.read() parsed = plistlib.loads(data) if play_state == const.PLAY_STATE_LOADING: if 'duration' in parsed: play_state = const.PLAY_STATE_PLAYING elif 'readyToPlay' not in parsed: play_state = const.PLAY_STATE_NO_MEDIA break elif play_state == const.PLAY_STATE_PLAYING: if 'duration' not in parsed: play_state = const.PLAY_STATE_NO_MEDIA break finally: if info is not None: info.close() yield from asyncio.sleep(1, loop=self.loop)
def read_bplist(data, start, length): """Extract a binary plist from a position in a sequence.""" # TODO: pylint doesn't find FMT_BINARY, why? # pylint: disable=no-member return plistlib.loads(data[start:start+length], fmt=plistlib.FMT_BINARY) # pylint: disable=unused-argument
def __ipa_parse(file_path: str): """ ??ipa? :param file_path: ipa?? :return: PackageParse """ ipa_file = ZipFile(file_path) # ??info.plist?? ns = [n for n in ipa_file.namelist() if Regex.IPAInfoPlistPath.match(n)] if not ns: log.warning('parse info.plist failure: {}'.format(file_path)) return plist_path = ns[-1] # ??plist plist_data = ipa_file.read(plist_path) plist_file = plistlib.loads(plist_data) # ??icon'CFBundleIconFiles' (4400546488) if plist_file.get('CFBundleIconFiles'): icon_name = plist_file['CFBundleIconFiles'][-1] else: if plist_file.get('CFBundleIcons'): icon_dict = plist_file['CFBundleIcons'] elif plist_file.get('CFBundleIcons'): icon_dict = plist_file['CFBundleIcons~ipad'] else: log.warning('parse icon failure: {}'.format(file_path)) return icon_name = icon_dict['CFBundlePrimaryIcon']['CFBundleIconFiles'][-1] log.debug('parse icon name: {}'.format(icon_name)) # ??icon?? re_icon_name_end = '(@\dx)\.png' if not icon_name.endswith('.png') else '' re_icon_name = re.compile('([^/]+/){{2}}{}{}'.format(icon_name, re_icon_name_end)) ns = [n for n in ipa_file.namelist() if re_icon_name.match(n)] if not ns: log.warning('read icon failure: {}'.format(file_path)) return icon_path = ns[-1] log.debug('parse icon path: {}'.format(icon_path)) # ??? version_number = plist_file['CFBundleShortVersionString'] # build? build_number = plist_file['CFBundleVersion'] # ?? package_name = plist_file['CFBundleIdentifier'] # app?? app_name = plist_file['CFBundleDisplayName'] if plist_file.get('CFBundleDisplayName') else plist_file[ 'CFBundleName'] log.debug( 'app: {}, V{} build {}, package: {}'.format(app_name, version_number, build_number, package_name)) return PackageParse(ipa_file, AppType.iOS, package_name, app_name, icon_path, version_number, build_number)