Python plistlib.readPlistFromString() Examples
The following are 30
code examples of plistlib.readPlistFromString().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
plistlib
, or try the search function
.
Example #1
Source File: ds.py From macops with Apache License 2.0 | 7 votes |
def _GetCSPSearchPathForPath(path): """Returns list of search nodes for a given path. Args: path: One of '/Search' or '/Search/Contacts' only. Returns: nodes: list of search nodes for given path. Raises: DSException: Unable to retrieve search nodes in path. """ command = [_DSCL, '-plist', path, '-read', '/', 'CSPSearchPath'] (stdout, stderr, unused_returncode) = gmacpyutil.RunProcess(command) result = plistlib.readPlistFromString(stdout) if 'dsAttrTypeStandard:CSPSearchPath' in result: search_nodes = result['dsAttrTypeStandard:CSPSearchPath'] return search_nodes else: raise DSException('Unable to retrieve search nodes: %s' % stderr)
Example #2
Source File: cpu_cores.py From unearth with Apache License 2.0 | 6 votes |
def fact(): """Returns the number of CPU cores""" result = "None" try: proc = subprocess.Popen( ["/usr/sbin/system_profiler", "SPHardwareDataType", "-xml"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = proc.communicate() except (IOError, OSError): stdout = None if stdout: d = plistlib.readPlistFromString(stdout.strip()) result = d[0]["_items"][0]["number_processors"] return {factoid: result}
Example #3
Source File: uuid_device.py From plugin.video.netflix with MIT License | 6 votes |
def _parse_osx_xml_plist_data(data): import plistlib import re dict_values = {} try: # Python 2 xml_data = plistlib.readPlistFromString(data) except AttributeError: # Python => 3.4 # pylint: disable=no-member xml_data = plistlib.loads(data) items_dict = xml_data[0]['_items'][0] r = re.compile(r'.*UUID.*') # Find to example "platform_UUID" key uuid_keys = list(filter(r.match, list(items_dict.keys()))) if uuid_keys: dict_values['UUID'] = items_dict[uuid_keys[0]] if not uuid_keys: r = re.compile(r'.*serial.*number.*') # Find to example "serial_number" key serialnumber_keys = list(filter(r.match, list(items_dict.keys()))) if serialnumber_keys: dict_values['serialnumber'] = items_dict[serialnumber_keys[0]] return dict_values
Example #4
Source File: checkipa.py From iOS-private-api-checker with GNU General Public License v2.0 | 6 votes |
def extract_provision_data(self): extract_info = self.get_filename_from_ipa('Provision') zip_obj = extract_info['zip_obj'] provision_filename = extract_info['filename'] data = {} if provision_filename == '': self.errors.append('embedded.mobileprovision file not found in IPA') else: content = zip_obj.read(provision_filename) match = ParseIPA.provision_xml_rx.search(content) if (match is not None): provision_xml_content = match.group() data = plistlib.readPlistFromString(provision_xml_content) else: self.errors.append('unable to parse embedded.mobileprovision file') self.provision_data = data # end extract_provision_data
Example #5
Source File: installapplications.py From installapplications with Apache License 2.0 | 6 votes |
def checkreceipt(packageid): try: cmd = ['/usr/sbin/pkgutil', '--pkg-info-plist', packageid] proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate() receiptout = output[0] if receiptout: plist = plistlib.readPlistFromString(receiptout) version = plist['pkg-version'] else: version = '0.0.0.0.0' return version except Exception: version = '0.0.0.0.0' return version
Example #6
Source File: plist_service.py From pymobiledevice with GNU General Public License v3.0 | 6 votes |
def recvPlist(self): payload = self.recv_raw() if not payload: return bplist_header = "bplist00" xml_header = "<?xml" if PY3: bplist_header = b"bplist00" xml_header = b"<?xml" if payload.startswith(bplist_header): if PY3: return plistlib.readPlistFromString(payload) else: from pymobiledevice.util.bplist import BPlistReader return BPlistReader(payload).parse() elif payload.startswith(xml_header): #HAX lockdown HardwarePlatform with null bytes payload = sub('[^\w<>\/ \-_0-9\"\'\\=\.\?\!\+]+','', payload.decode('utf-8')).encode('utf-8') return plistlib.readPlistFromString(payload) else: raise Exception("recvPlist invalid data : %s" % payload[:100].encode("hex"))
Example #7
Source File: uuid_device.py From plugin.video.hbogoeu with GNU General Public License v2.0 | 6 votes |
def _parse_osx_xml_plist_data(data): import plistlib import re dict_values = {} try: # Python 2 xml_data = plistlib.readPlistFromString(data) except AttributeError: # Python => 3.4 # pylint: disable=no-member xml_data = plistlib.loads(data) items_dict = xml_data[0]['_items'][0] r = re.compile(r'.*UUID.*') # Find to example "platform_UUID" key uuid_keys = list(filter(r.match, list(items_dict.keys()))) if uuid_keys: dict_values['UUID'] = items_dict[uuid_keys[0]] if not uuid_keys: r = re.compile(r'.*serial.*number.*') # Find to example "serial_number" key serialnumber_keys = list(filter(r.match, list(items_dict.keys()))) if serialnumber_keys: dict_values['serialnumber'] = items_dict[serialnumber_keys[0]] return dict_values
Example #8
Source File: agent.py From ccs-calendarserver with Apache License 2.0 | 6 votes |
def gatewayCommandReceived(self, command): """ Process a command via gateway.Runner @param command: GatewayAMPCommand @returns: a deferred returning a dict """ command = readPlistFromString(command) output = cStringIO.StringIO() from calendarserver.tools.gateway import Runner runner = Runner( self.store, [command], output=output ) try: yield runner.run() result = output.getvalue() output.close() except Exception as e: error = {"Error": str(e)} result = writePlistToString(error) output.close() returnValue(dict(result=result))
Example #9
Source File: cpu_l3_cache.py From unearth with Apache License 2.0 | 6 votes |
def fact(): """Returns the CPU L3 cache""" result = "None" try: proc = subprocess.Popen( ["/usr/sbin/system_profiler", "SPHardwareDataType", "-xml"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = proc.communicate() except (IOError, OSError): stdout = None if stdout: d = plistlib.readPlistFromString(stdout.strip()) result = d[0]["_items"][0]["l3_cache"] return {factoid: result}
Example #10
Source File: drive_medium.py From unearth with Apache License 2.0 | 6 votes |
def fact(): """Returns the boot drive medium""" result = "None" try: proc = subprocess.Popen( ["/usr/sbin/diskutil", "info", "-plist", "/"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = proc.communicate() except (IOError, OSError): stdout = None if stdout: d = plistlib.readPlistFromString(stdout.strip()) if d.get("CoreStorageCompositeDisk", False): result = "fusion" elif d.get("RAIDMaster", False): result = "raid" else: result = "ssd" if d.get("SolidState", False) else "rotational" return {factoid: result}
Example #11
Source File: adultswim.py From plugin.video.ustvvod with GNU General Public License v2.0 | 6 votes |
def masterlist(): master_db = [] master_dict = {} master_data = connection.getURL(SHOWS) master_tree = plistlib.readPlistFromString(master_data) for master_item in master_tree: master_name = common.smart_utf8(master_item['name']) tvdb_name = common.get_show_data(master_name, SITE, 'seasons')[-1] if tvdb_name not in master_dict.keys(): master_dict[tvdb_name] = master_item['show-id'] else: master_dict[tvdb_name] = master_dict[tvdb_name] + ',' + master_item['show-id'] for master_name in master_dict: season_url = master_dict[master_name] master_db.append((master_name, SITE, 'seasons', season_url)) return master_db
Example #12
Source File: fmm_status.py From unearth with Apache License 2.0 | 6 votes |
def fact(): """Return the Find My Mac status""" result = False try: proc = subprocess.Popen( ["/usr/sbin/nvram", "-x", "-p", "status"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, _ = proc.communicate() except (IOError, OSError): stdout = "" if stdout: if plistlib.readPlistFromString(stdout).get("fmm-mobileme-token-FMM", None): result = True return {factoid: result}
Example #13
Source File: password_changed.py From unearth with Apache License 2.0 | 5 votes |
def fact(): """Gets the date of last password change""" password_changed = "None" # for 10.10+ or non-migrated accounts username = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if username: task = subprocess.check_output( ["/usr/bin/dscl", ".", "read", "Users/" + username, "accountPolicyData"] ) plist = plistlib.readPlistFromString("\n".join(task.split()[1:])) if "passwordLastSetTime" in plist.keys(): password_changed = datetime.datetime.utcfromtimestamp( plist["passwordLastSetTime"] ).date() else: # for 10.9.x and lower, or migrated accounts task = subprocess.Popen( [ "/usr/bin/dscl", ".", "read", "Users/" + username, "PasswordPolicyOptions", ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) (out, err) = task.communicate() if not err: plist = plistlib.readPlistFromString("\n".join(out.split()[1:])) if "passwordLastSetTime" in plist.keys(): password_changed = plist["passwordLastSetTime"].date() return {factoid: str(password_changed)}
Example #14
Source File: changeip_calendar.py From ccs-calendarserver with Apache License 2.0 | 5 votes |
def sendCommand(commandDict, configFile=None): args = [CALENDARSERVER_CONFIG] if configFile is not None: args.append("-f {}".format(configFile)) child = subprocess.Popen( args=args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) commandString = plistlib.writePlistToString(commandDict) log("Sending to calendarserver_config: {}".format(commandString)) output, error = child.communicate(input=commandString) log("Output from calendarserver_config: {}".format(output)) if child.returncode: log( "Error from calendarserver_config: {}, {}".format( child.returncode, error ) ) return None else: return plistlib.readPlistFromString(output)["result"]
Example #15
Source File: console_user_is_admin.py From unearth with Apache License 2.0 | 5 votes |
def fact(): """Returns whether current console user is an admin""" result = False cmd = ["/usr/bin/dscl", "-plist", ".", "read", "/Groups/admin"] output = subprocess.check_output(cmd) d = plistlib.readPlistFromString(output)["dsAttrTypeStandard:GroupMembership"] console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if console_user in d: result = True return {factoid: result}
Example #16
Source File: usbmux.py From pymobiledevice with GNU General Public License v3.0 | 5 votes |
def getpacket(self): resp, tag, payload = BinaryProtocol.getpacket(self) if resp != self.TYPE_PLIST: raise MuxError("Received non-plist type %d"%resp) if PY3: payload = plistlib.loads(payload) else: payload = plistlib.readPlistFromString(payload) return payload.get('MessageType', ''), tag, payload
Example #17
Source File: __init__.py From pymobiledevice with GNU General Public License v3.0 | 5 votes |
def parsePlist(s): return plistlib.readPlistFromString(s) #http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
Example #18
Source File: pullTags.py From panotti with MIT License | 5 votes |
def pullTags_one_file(file_list, new_main_folder, file_index): # We actually pull the tags and create the directories & symbolic links as we go, # and let the OS/filesystem handle 'collisions' if more than one process is trying to create the same thing infile = file_list[file_index] #print('infile = ',infile) output = subprocess.check_output(['mdls','-plist','-', infile]) # mdls is an Apple command-line utility plist = readPlistFromString(output) #print(plist) print_every = 100 if (0 == file_index % print_every): print("pullTags: File ",file_index,"/",len(file_list),": ",infile,sep="") for key in keys_to_use: #print(" Checking key = ",key) try: tags = plist[key] if tags: # guard against blank tags if isinstance(tags, str): tags = [tags] # just make it a length-1 list #print(" key = ",key,", tags (list):") for tag in tags: tag = re.sub('[^a-zA-Z\d\ ]|( ){2,}','_',tag ) # whitelist only certain characters. e.g. "4/4"->"4_4" #tag = tag.replace("/", "-").replace(";", "-").replace("\\", "-").replace(" ", "_").replace #print(" [",tag,']',sep="") if tag: # guard against blank tags new_folder = new_main_folder+'/'+tag make_dir(new_folder) link_name = new_folder+'/'+os.path.basename(infile) make_link(infile, link_name) except: #print("Key error: File",infile,"doesn't contain key",key) pass return
Example #19
Source File: test_plistlib.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_nondictroot(self): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.readPlistFromString(plistlib.writePlistToString(test1)) result2 = plistlib.readPlistFromString(plistlib.writePlistToString(test2)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
Example #20
Source File: usbmux.py From pymobiledevice with GNU General Public License v3.0 | 5 votes |
def get_pair_record(self, udid): tag = self.pkttag self.pkttag += 1 payload = {"PairRecordID": udid} self.proto.sendpacket("ReadPairRecord", tag, payload) _, recvtag, data = self.proto.getpacket() if recvtag != tag: raise MuxError("Reply tag mismatch: expected %d, got %d" % (tag, recvtag)) if PY3: pair_record = data['PairRecordData'] pair_record = plistlib.loads(pair_record) else: pair_record = data['PairRecordData'].data pair_record = plistlib.readPlistFromString(pair_record) return pair_record
Example #21
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_nondictroot(self): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.readPlistFromString(plistlib.writePlistToString(test1)) result2 = plistlib.readPlistFromString(plistlib.writePlistToString(test2)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
Example #22
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_appleformatting(self): pl = plistlib.readPlistFromString(TESTDATA) data = plistlib.writePlistToString(pl) self.assertEqual(data, TESTDATA, "generated data was not identical to Apple's output")
Example #23
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]}]}} self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
Example #24
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_indentation_dict(self): data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': plistlib.Data(b'aaaaaa')}}}}}}}}} self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
Example #25
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_indentation_array(self): data = [[[[[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]]]] self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
Example #26
Source File: test_plistlib.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_string(self): pl = self._create() data = plistlib.writePlistToString(pl) pl2 = plistlib.readPlistFromString(data) self.assertEqual(dict(pl), dict(pl2)) data2 = plistlib.writePlistToString(pl2) self.assertEqual(data, data2)
Example #27
Source File: test_project_management.py From firebase-admin-python with Apache License 2.0 | 5 votes |
def test_get_ios_app_config(ios_app, project_id): config = ios_app.get_config() # In Python 2.7, the plistlib module works with strings, while in Python 3, it is significantly # redesigned and works with bytes objects instead. try: plist = plistlib.loads(config.encode('utf-8')) except AttributeError: # Python 2.7 plistlib does not have the loads attribute. plist = plistlib.readPlistFromString(config) # pylint: disable=no-member assert plist['BUNDLE_ID'] == TEST_APP_BUNDLE_ID assert plist['PROJECT_ID'] == project_id assert plist['GOOGLE_APP_ID'] == ios_app.app_id
Example #28
Source File: osx.py From luci-py with Apache License 2.0 | 5 votes |
def _read_plist(data): if six.PY2: return plistlib.readPlistFromString(data) else: return plistlib.loads(data) ## Public API.
Example #29
Source File: ampsim.py From ccs-calendarserver with Apache License 2.0 | 5 votes |
def config(self, plist): from sys import stderr cfg = readPlistFromString(plist) addObserver(self.emit) sim = LoadSimulator.fromConfig(cfg) sim.records = self.records sim.attachServices(stderr) return {}
Example #30
Source File: agent.py From ccs-calendarserver with Apache License 2.0 | 5 votes |
def render_POST(self, request): """ Take the body of the POST request and feed it to gateway.Runner(); return the result as the response body. """ self.inactivityDetector.activity() def onSuccess(result, output): txt = output.getvalue() output.close() request.write(txt) request.finish() def onError(failure): message = failure.getErrorMessage() tbStringIO = cStringIO.StringIO() failure.printTraceback(file=tbStringIO) tbString = tbStringIO.getvalue() tbStringIO.close() error = { "Error": message, "Traceback": tbString, } log.error("command failed {error}", error=failure) request.write(writePlistToString(error)) request.finish() from calendarserver.tools.gateway import Runner body = request.content.read() command = readPlistFromString(body) output = cStringIO.StringIO() runner = Runner(self.store, [command], output=output) d = runner.run() d.addCallback(onSuccess, output) d.addErrback(onError) return NOT_DONE_YET