我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用plistlib.readPlist()。
def _mac_ver_xml(): fn = '/System/Library/CoreServices/SystemVersion.plist' if not os.path.exists(fn): return None try: import plistlib except ImportError: return None pl = plistlib.readPlist(fn) release = pl['ProductVersion'] versioninfo=('', '', '') machine = os.uname()[4] if machine in ('ppc', 'Power Macintosh'): # for compatibility with the gestalt based code machine = 'PowerPC' return release,versioninfo,machine
def _macosx_vers(_cache=[]): if not _cache: import platform version = platform.mac_ver()[0] # fallback for MacPorts if version == '': import plistlib plist = '/System/Library/CoreServices/SystemVersion.plist' if os.path.exists(plist): if hasattr(plistlib, 'readPlist'): plist_content = plistlib.readPlist(plist) if 'ProductVersion' in plist_content: version = plist_content['ProductVersion'] _cache.append(version.split('.')) return _cache[0]
def differences(file_a, file_b): if all([sys.argv[1].endswith('.plist'), sys.argv[2].endswith('.plist')]): files = sorted([x for x in [sys.argv[1], sys.argv[2]]]) file_a = files[0] file_b = files[1] pkg_set_a = plistlib.readPlist(file_a)['Packages'] pkg_set_b = plistlib.readPlist(file_b)['Packages'] pkg_set_a = [pkg_set_a[x]['DownloadName'] for x in pkg_set_a] pkg_set_b = [pkg_set_b[x]['DownloadName'] for x in pkg_set_b] not_in_pkg_set_a = [x for x in pkg_set_b if x not in pkg_set_a] # common_pkgs = {x for x in pkg_set_b if x in pkg_set_a} print 'The following packages in {} are not in {}'.format(file_b, file_a) for pkg in not_in_pkg_set_a: print pkg else: print 'Usage: {} <file a> <file b>'.format(sys.argv[0]) sys.exit(1)
def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, dummy_plistFormat, error = ( NSPropertyListSerialization. propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None)) if dataObject is None: if error: error = error.encode('ascii', 'ignore') else: error = "Unknown error" errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def renameUFOLib(ufoPath, newNames, dryRun=False, print=print): filename = os.path.join(ufoPath, 'lib.plist') plist = plistlib.readPlist(filename) glyphOrder = plist.get('public.glyphOrder') if glyphOrder is not None: plist['public.glyphOrder'] = renameStrings(glyphOrder, newNames) roboSort = plist.get('com.typemytype.robofont.sort') if roboSort is not None: for entry in roboSort: if isinstance(entry, dict) and entry.get('type') == 'glyphList': asc = entry.get('ascending') desc = entry.get('descending') if asc is not None: entry['ascending'] = renameStrings(asc, newNames) if desc is not None: entry['descending'] = renameStrings(desc, newNames) print('Writing', filename) if not dryRun: plistlib.writePlist(plist, filename)
def renameUFOGroups(ufoPath, newNames, dryRun=False, print=print): filename = os.path.join(ufoPath, 'groups.plist') plist = None try: plist = plistlib.readPlist(filename) except: return didChange = False for groupName, glyphNames in plist.items(): for i in range(len(glyphNames)): name = glyphNames[i] if name in newNames: didChange = True glyphNames[i] = newNames[name] if didChange: print('Writing', filename) if not dryRun: plistlib.writePlist(plist, filename)
def testWidthNameConversion(self): widthName1To2 = { "Ultra-condensed" : 1, "Extra-condensed" : 2, "Condensed" : 3, "Semi-condensed" : 4, "Medium (normal)" : 5, "Semi-expanded" : 6, "Expanded" : 7, "Extra-expanded" : 8, "Ultra-expanded" : 9 } for old, new in widthName1To2.items(): infoObject = self.makeInfoObject() infoObject.openTypeOS2WidthClass = new writer = UFOWriter(self.dstDir, formatVersion=1) writer.writeInfo(infoObject) writtenData = self.readPlist() self.assertEqual(writtenData["widthName"], old)
def loadKerning(filename): kerning = plistlib.readPlist(filename) # <dict> # <key>@KERN_LEFT_A</key> # <dict> # <key>@KERN_RIGHT_C</key> # <integer>-96</integer> leftIndex = {} # { glyph-name => <ref to plist right-hand side dict> } rightIndex = {} # { glyph-name => [(left-hand-side-name, kernVal), ...] } rightGroupIndex = {} # { group-name => [(left-hand-side-name, kernVal), ...] } for leftName, right in kerning.iteritems(): if leftName[0] != '@': leftIndex[leftName] = right for rightName, kernVal in right.iteritems(): if rightName[0] != '@': rightIndex.setdefault(rightName, []).append((leftName, kernVal)) else: rightGroupIndex.setdefault(rightName, []).append((leftName, kernVal)) return kerning, leftIndex, rightIndex, rightGroupIndex
def create_app_clone(self, name, specialise_plist, remove_doc_types=True): print('\nCreating ' + name) cc_dir = os.path.join(self.contents_dir, name, 'Contents') exe_dir = join(cc_dir, 'MacOS') os.makedirs(exe_dir) for x in os.listdir(self.contents_dir): if x.endswith('.app'): continue if x == 'Info.plist': plist = plistlib.readPlist(join(self.contents_dir, x)) specialise_plist(plist) if remove_doc_types: plist.pop('CFBundleDocumentTypes') exe = plist['CFBundleExecutable'] # We cannot symlink the bundle executable as if we do, # codesigning fails nexe = plist['CFBundleExecutable'] = exe + '-placeholder-for-codesigning' shutil.copy2(join(self.contents_dir, 'MacOS', exe), join(exe_dir, nexe)) exe = join(exe_dir, plist['CFBundleExecutable']) plistlib.writePlist(plist, join(cc_dir, x)) elif x == 'MacOS': for item in os.listdir(join(self.contents_dir, 'MacOS')): os.symlink('../../../MacOS/' + item, join(exe_dir, item)) else: os.symlink(join('../..', x), join(cc_dir, x))
def _WritePkgInfo(self, info_plist): """This writes the PkgInfo file from the data stored in Info.plist.""" plist = plistlib.readPlist(info_plist) if not plist: return # Only create PkgInfo for executable types. package_type = plist['CFBundlePackageType'] if package_type != 'APPL': return # The format of PkgInfo is eight characters, representing the bundle type # and bundle signature, each four characters. If that is missing, four # '?' characters are used instead. signature_code = plist.get('CFBundleSignature', '????') if len(signature_code) != 4: # Wrong length resets everything, too. signature_code = '?' * 4 dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') fp = open(dest, 'w') fp.write('%s%s' % (package_type, signature_code)) fp.close()
def _LoadPlistMaybeBinary(self, plist_path): """Loads into a memory a plist possibly encoded in binary format. This is a wrapper around plistlib.readPlist that tries to convert the plist to the XML format if it can't be parsed (assuming that it is in the binary format). Args: plist_path: string, path to a plist file, in XML or binary format Returns: Content of the plist as a dictionary. """ try: # First, try to read the file using plistlib that only supports XML, # and if an exception is raised, convert a temporary copy to XML and # load that copy. return plistlib.readPlist(plist_path) except: pass with tempfile.NamedTemporaryFile() as temp: shutil.copy2(plist_path, temp.name) subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) return plistlib.readPlist(temp.name)
def readPlist(pathOrFile): """Raises NotBinaryPlistException, InvalidPlistException""" didOpen = False result = None if isinstance(pathOrFile, (six.binary_type, six.text_type)): pathOrFile = open(pathOrFile, 'rb') didOpen = True try: reader = PlistReader(pathOrFile) result = reader.parse() except NotBinaryPlistException as e: try: pathOrFile.seek(0) result = plistlib.readPlist(pathOrFile) result = wrapDataObject(result, for_binary=True) except Exception as e: raise InvalidPlistException(e) if didOpen: pathOrFile.close() return result
def _load_info_plist(self): """Load workflow info from ``info.plist``.""" # info.plist should be in the directory above this one self._info = plistlib.readPlist(self.workflowfile('info.plist')) self._info_loaded = True
def _macosx_vers(_cache=[]): if not _cache: version = platform.mac_ver()[0] # fallback for MacPorts if version == '': plist = '/System/Library/CoreServices/SystemVersion.plist' if os.path.exists(plist): if hasattr(plistlib, 'readPlist'): plist_content = plistlib.readPlist(plist) if 'ProductVersion' in plist_content: version = plist_content['ProductVersion'] _cache.append(version.split('.')) return _cache[0]
def _load_info_plist(self): """Load workflow info from ``info.plist`` """ self._info = plistlib.readPlist(self._info_plist) self._info_loaded = True
def changeBuildVersion(self): plist = plistlib.readPlist(self.plist_path) plist['CFBundleVersion'] = self.build_date if self.build_version is not None: build_version_list = self.build_version.split('.') CFBundleShortVersionString = '.'.join(build_version_list[:3]) plist['CFBundleShortVersionString'] = CFBundleShortVersionString.rstrip('.0') else: self.build_version = plist['CFBundleShortVersionString'] plistlib.writePlist(plist, self.plist_path)
def cache_server(self): '''Gets the Caching/Tetherator server address, by checking Caching/Tetherator configurations.''' # Two places a config file can exist depending on whether this is # Caching Server in Server.app or a tetherator machine. config_plists = [self.configuration['tetheratorConfigPlist'], self.configuration['cacheServerConfigPlist']] try: plist = [x for x in config_plists if os.path.exists(x)][0] self.log.debug('Found caching server plist: %s' % plist) except: plist = False self.log.debug('No caching server plist found.') if plist: # Fall back to testing if Caching Server/Server.app or tetherator try: port = readPlist(plist)['LastPort'] except: try: port = readPlist(plist)['Port'] except: self.log.debug('No port for caching server found in %s' % plist) # NOQA raise Exception('No port found.') if port: return 'http://localhost:%s' % port else: return self.cache_locator() else: return self.cache_locator()
def load_config(self, config_file): '''Loads configuration from the local configuration plist''' # Make sure configuration plist is in the same directory as script try: self.log.debug('load_config() success') return readPlist(config_file) except Exception as e: self.log.debug('load_config() failed: %s' % e) raise e
def tetherator_status(self, plist): '''Gets the status of tethered cache server, returns True if running, False if not''' try: if readPlist(plist)['Activated']: return True else: return False except: return False