我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用plistlib.writePlistToString()。
def writeContents(self): """Write the contents.plist file out to disk. Call this method when you're done writing glyphs. """ from plistlib import writePlistToString contentsPath = os.path.join(self.dirName, "contents.plist") # We need to force Unix line endings, even in OS9 MacPython in FL, # so we do the writing to file ourselves. plist = writePlistToString(self.contents) f = open(contentsPath, WRITE_MODE) f.write(plist) f.close() # read caching
def writePlistToString(rootObject, binary=True): if not binary: rootObject = wrapDataObject(rootObject, binary) if hasattr(plistlib, "dumps"): return plistlib.dumps(rootObject) elif hasattr(plistlib, "writePlistToBytes"): return plistlib.writePlistToBytes(rootObject) else: return plistlib.writePlistToString(rootObject) else: ioObject = io.BytesIO() writer = PlistWriter(ioObject) writer.writeRoot(rootObject) return ioObject.getvalue()
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)
def test_indentation_array(self): data = [[[[[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]]]] self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
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)
def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]}]}} self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
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")
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)
def writePlistToString(rootObject, binary=True): if not binary: rootObject = wrapDataObject(rootObject, binary) if six.PY3: return plistlib.writePlistToBytes(rootObject) else: return plistlib.writePlistToString(rootObject) else: io = six.BytesIO() writer = PlistWriter(io) writer.writeRoot(rootObject) return io.getvalue()
def writePlist(obj, path): if not os.path.isabs(path): path = storage(path) s = plistlib.writePlistToString(obj) with codecs.open(path, "w", "utf-8") as f: f.write(s)
def sendpacket(self, req, tag, payload={}): payload['ClientVersionString'] = 'usbmux.py by marcan' if isinstance(req, int): req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2] payload['MessageType'] = req payload['ProgName'] = 'tcprelay' BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
def gen_launchd(tw, config, writer): devpibin = py.path.local(sys.argv[0]) plist_content = write_plist_to_bytes(OrderedDict([ ("Label", "net.devpi"), ("ProgramArguments", [str(devpibin)] + config.args._raw), ("RunAtLoad", True), ])) writer("net.devpi.plist", plist_content)
def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): """Copies the |source| Info.plist to the destination directory |dest|.""" # Read the source Info.plist into memory. fd = open(source, 'r') lines = fd.read() fd.close() # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). plist = plistlib.readPlistFromString(lines) if keys: plist = dict(plist.items() + json.loads(keys[0]).items()) lines = plistlib.writePlistToString(plist) # Go through all the environment variables and replace them as variables in # the file. IDENT_RE = re.compile(r'[/\s]') for key in os.environ: if key.startswith('_'): continue evar = '${%s}' % key evalue = os.environ[key] lines = string.replace(lines, evar, evalue) # Xcode supports various suffices on environment variables, which are # all undocumented. :rfc1034identifier is used in the standard project # template these days, and :identifier was used earlier. They are used to # convert non-url characters into things that look like valid urls -- # except that the replacement character for :identifier, '_' isn't valid # in a URL either -- oops, hence :rfc1034identifier was born. evar = '${%s:identifier}' % key evalue = IDENT_RE.sub('_', os.environ[key]) lines = string.replace(lines, evar, evalue) evar = '${%s:rfc1034identifier}' % key evalue = IDENT_RE.sub('-', os.environ[key]) lines = string.replace(lines, evar, evalue) # Remove any keys with values that haven't been replaced. lines = lines.split('\n') for i in range(len(lines)): if lines[i].strip().startswith("<string>${"): lines[i] = None lines[i - 1] = None lines = '\n'.join(filter(lambda x: x is not None, lines)) # Write out the file with variables replaced. fd = open(dest, 'w') fd.write(lines) fd.close() # Now write out PkgInfo file now that the Info.plist file has been # "compiled". self._WritePkgInfo(dest) if convert_to_binary == 'True': self._ConvertToBinary(dest)
def setUp(self): fp = FilePath(self.mktemp()) fp.makedirs() from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor, defer d = defer.Deferred() class JustLetMeMoveOn(Protocol): def connectionMade(self): d.callback(None) self.transport.abortConnection() f = Factory() f.protocol = JustLetMeMoveOn port = reactor.listenTCP(0, f, interface="127.0.0.1") @self.addCleanup def goodbyePort(): return port.stopListening() env = dict(os.environ) env["TESTING_PORT"] = repr(port.getHost().port) self.stdout = fp.child("stdout.txt") self.stderr = fp.child("stderr.txt") self.launchLabel = ("org.calendarserver.UNIT-TESTS." + str(os.getpid()) + "." + self.id()) plist = { "Label": self.launchLabel, "ProgramArguments": [sys.executable, "-m", __name__, self.id()], "EnvironmentVariables": env, "KeepAlive": False, "StandardOutPath": self.stdout.path, "StandardErrorPath": self.stderr.path, "Sockets": { "Awesome": [{"SecureSocketWithKey": "GeneratedSocket"}] }, "RunAtLoad": True, "Debug": True, } self.job = fp.child("job.plist") self.job.setContent(plistlib.writePlistToString(plist)) child = Popen( args=[ "launchctl", "load", self.job.path, ], stdout=PIPE, stderr=PIPE, ) _ignore_output, error = child.communicate() if child.returncode != 0 or error: raise SkipTest("launchctl cannot run on this system") return d
def build_system_configuration_profile(device, install = False): # Configuration Profiles are only valid on OS X. if device.os != Device.OSX: return plist = { } plist['PayloadDisplayName'] = 'System Device Configuration' plist['PayloadDescription'] = 'Managed Preferences for Device' plist['PayloadIdentifier'] = settings.MANAGED_PROFILE_IDENTIFIER + '.ManagedPreferences' plist['PayloadOrganization'] = settings.ORGANIZATION plist['PayloadRemovalDisallowed'] = False plist['PayloadVersion'] = 1 plist['PayloadType'] = 'Configuration' plist['PayloadScope'] = 'System' plist['PayloadUUID'] = str(uuid.uuid4()) plist['PayloadContent'] = [ ] apps = build_custom_preference_profile(device) for app in apps: payload = { } payload['PayloadEnabled'] = True payload['PayloadType'] = 'com.apple.ManagedClient.preferences' payload['PayloadUUID'] = str(uuid.uuid4()) payload['PayloadIdentifier'] = plist['PayloadIdentifier'] + '.alacarte.customsettings.' + payload['PayloadUUID'] payload['PayloadVerison'] = 1 payload['PayloadContent'] = { app: apps[app] } plist['PayloadContent'].append(payload) if DeviceProfile.objects.filter(device=device, identifier=plist['PayloadIdentifier']).count() == 0: profile = DeviceProfile(device=device) else: profile = DeviceProfile.objects.get(device=device, identifier=plist['PayloadIdentifier']) profile.name = plist['PayloadDisplayName'] profile.identifier = plist['PayloadIdentifier'] profile.uuid = plist['PayloadUUID'] profile.payload = plistlib.writePlistToString(plist) profile.save() if install == True: DeviceCommand.InstallProfile(device, profile) push.push_notification(device)