def WriteTo(self, target_path):
plistlib.writePlist(self._data, target_path)
python类writePlist()的实例源码
def SavePList(path, format, data):
"""Saves |data| as a Plist to |path| in the specified |format|."""
fd, name = tempfile.mkstemp()
try:
with os.fdopen(fd, 'w') as f:
plistlib.writePlist(data, f)
subprocess.check_call(['plutil', '-convert', format, '-o', path, name])
finally:
os.unlink(name)
def test_io(self):
pl = self._create()
plistlib.writePlist(pl, test_support.TESTFN)
pl2 = plistlib.readPlist(test_support.TESTFN)
self.assertEqual(dict(pl), dict(pl2))
def test_stringio(self):
from StringIO import StringIO
f = StringIO()
pl = self._create()
plistlib.writePlist(pl, f)
pl2 = plistlib.readPlist(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def test_cstringio(self):
from cStringIO import StringIO
f = StringIO()
pl = self._create()
plistlib.writePlist(pl, f)
pl2 = plistlib.readPlist(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def test_io(self):
pl = self._create()
plistlib.writePlist(pl, test_support.TESTFN)
pl2 = plistlib.readPlist(test_support.TESTFN)
self.assertEqual(dict(pl), dict(pl2))
def test_stringio(self):
from StringIO import StringIO
f = StringIO()
pl = self._create()
plistlib.writePlist(pl, f)
pl2 = plistlib.readPlist(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def test_cstringio(self):
from cStringIO import StringIO
f = StringIO()
pl = self._create()
plistlib.writePlist(pl, f)
pl2 = plistlib.readPlist(StringIO(f.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
def writePlist(plist, path):
plist.write(path)
def makeMpkgPlist(path):
vers = getFullVersion()
major, minor = getVersionMajorMinor()
pl = Plist(
CFBundleGetInfoString="Python %s"%(vers,),
CFBundleIdentifier='org.python.Python',
CFBundleName='Python',
CFBundleShortVersionString=vers,
IFMajorVersion=major,
IFMinorVersion=minor,
IFPkgFlagComponentDirectory="Contents/Packages",
IFPkgFlagPackageList=[
dict(
IFPkgFlagPackageLocation='%s-%s.pkg'%(item['name'], getVersion()),
IFPkgFlagPackageSelection=item.get('selected', 'selected'),
)
for item in pkg_recipes()
],
IFPkgFormatVersion=0.10000000149011612,
IFPkgFlagBackgroundScaling="proportional",
IFPkgFlagBackgroundAlignment="left",
IFPkgFlagAuthorizationAction="RootAuthorization",
)
writePlist(pl, path)
def writePlist(rootObject, pathOrFile, binary=True):
if not binary:
rootObject = wrapDataObject(rootObject, binary)
return plistlib.writePlist(rootObject, pathOrFile)
else:
didOpen = False
if isinstance(pathOrFile, (six.binary_type, six.text_type)):
pathOrFile = open(pathOrFile, 'wb')
didOpen = True
writer = PlistWriter(pathOrFile)
result = writer.writeRoot(rootObject)
if didOpen:
pathOrFile.close()
return result
def update_bundle_info(bundle_path, version, repo):
info_plist_path = os.path.join(bundle_path, 'Contents', 'Info.plist')
info_plist = plistlib.readPlist(info_plist_path)
info_plist['CFBundleVersion'] = version
info_plist['LBDescription']['LBDownloadURL'] = expand_url_template(
'https://github.com/%s/releases/download/%s/%s', repo,
tag_for_version(version), archive_dir_name(bundle_path, version)[1])
plistlib.writePlist(info_plist, info_plist_path)
def BuildPF():
CustomPrefList = buildlistdir("./Preferences")
Plist = plistlib.readPlist('./BasePreferences.plist')
#Sort Modules
for key in ModuleDict.keys():
ModuleDict[key].sort()
#Start
SortedKeys=ModuleDict.keys()
for key in SortedKeys:
if len(ModuleDict[key])<=0:
continue
Dict = {
"cell": "PSGroupCell",
"label": key
}
Plist["items"].append(Dict)
for x in ModuleDict[key]:
CustomPrefPath = x + ".plist"
if (CustomPrefPath in CustomPrefList):
custom = plistlib.readPlist('./Preferences/' + CustomPrefPath)
Plist["items"].append(custom)
Dict = {
"cell": "PSSwitchCell",
"label": x,
"key": x,
"default": False,
"defaults": "naville.wtfjh"
}
Plist["items"].append(Dict)
Dict = {
"cell": "PSGroupCell",
"footerText": "https://github.com/Naville/WTFJH"
}
Plist["items"].append(Dict)
plistlib.writePlist(Plist, "./layout/Library/PreferenceLoader/Preferences/WTFJHPreferences.plist")
def _write_plist(self, plist):
"""Writes the given plist to the output file.
This method also converts it to binary format if "binary" is True in the
control struct.
Args:
plist: The plist to write to the output path in the control struct.
"""
path_or_file = self._control['output']
plistlib.writePlist(plist, path_or_file)
if self._control.get('binary') and isinstance(path_or_file, basestring):
subprocess.check_call(['plutil', '-convert', 'binary1', path_or_file])
def make_computer_manifest(given_serial):
'''Checks for the presence and validity of an existing manifest for this client in the repository.
Creates a new manifest if an existing one is not found or is invalid.'''
# Filesystem path for this computer's manifest:
computer_manifest_name = given_serial.upper() # if not already
computer_manifest_path = os.path.join(munki_repo.COMPUTER_MANIFESTS_PATH,computer_manifest_name)
# Control variable: should a new manifest be created?
# Assume yes, unless an existing manifest is found and is valid.
should_create_new_client_manifest = True
# Catch missing computer manifests directory:
if not os.path.exists(munki_repo.COMPUTER_MANIFESTS_PATH):
common.logging_error("Computers manifests directory not found at %s." % munki_repo.COMPUTER_MANIFESTS_PATH)
raise
# Check existing manifest for this client:
if os.path.exists(computer_manifest_path):
common.logging_info("Manifest for %s already in repository. Checking it." % computer_manifest_name)
try:
computer_manifest_dict = plistlib.readPlist(computer_manifest_path)
# Manifest already exists; do not overwrite if it's a valid dict!
if computer_manifest_dict:
should_create_new_client_manifest = False
common.logging_info("Manifest for %s should be left alone." % computer_manifest_name)
except xml.parsers.expat.ExpatError:
common.logging_error("Manifest for %s is invalid. Will recreate." % computer_manifest_name)
# Build a new client manifest if required:
if should_create_new_client_manifest:
common.logging_info("Creating new manifest for %s." % computer_manifest_name)
computer_manifest_dict = {}
computer_manifest_dict['managed_installs'] = []
computer_manifest_dict['managed_uninstalls'] = []
computer_manifest_dict['catalogs'] = munki_repo.CATALOG_ARRAY
computer_manifest_dict['included_manifests'] = ['groups/%s' % munki_repo.DEFAULT_GROUP]
try:
plistlib.writePlist(computer_manifest_dict,computer_manifest_path)
except TypeError:
common.logging_error("Failed to write manifest for %s." % computer_manifest_name)
def write_metadata_to_manifest(given_computer_manifest_name,given_metadata_key,given_metadata_value):
'''Modifes the given computer manifest's _metadata dict, adding (overwriting) the given key and value.
Given manifest must be present and a valid plist. Returns true if successful, false otherwise.'''
# Filesystem paths for the manifest:
given_computer_manifest_name = given_computer_manifest_name.upper() # if not already
computer_manifest_path = os.path.join(munki_repo.COMPUTER_MANIFESTS_PATH,given_computer_manifest_name)
# Catch missing manifest:
if not os.path.exists(computer_manifest_path):
common.logging_error("Computer manifest not found at %s." % computer_manifest_path)
return False
# Load manifest:
try:
computer_manifest_dict = plistlib.readPlist(computer_manifest_path)
except xml.parsers.expat.ExpatError:
common.logging_error("Computer manifest %s is invalid." % given_computer_manifest_name)
return False
# Load manifest metadata or start with blank:
try:
manifest_metadata_dict = computer_manifest_dict['_metadata']
except KeyError:
manifest_metadata_dict = {}
# Modify metadata dict:
common.logging_info("Adding %(key)s to %(manifest)s." % {'key':given_metadata_key,'manifest':given_computer_manifest_name})
manifest_metadata_dict[given_metadata_key] = given_metadata_value
computer_manifest_dict['_metadata'] = manifest_metadata_dict
# Save manifest:
try:
plistlib.writePlist(computer_manifest_dict,computer_manifest_path)
return True
except TypeError:
common.logging_error("Failed to write manifest for %s." % given_computer_manifest_name)
return False
def ExecMergeInfoPlist(self, output, *inputs):
"""Merge multiple .plist files into a single .plist file."""
merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output)
def _InstallEntitlements(self, entitlements, substitutions, overrides):
"""Generates and install the ${BundleName}.xcent entitlements file.
Expands variables "$(variable)" pattern in the source entitlements file,
add extra entitlements defined in the .mobileprovision file and the copy
the generated plist to "${BundlePath}.xcent".
Args:
entitlements: string, optional, path to the Entitlements.plist template
to use, defaults to "${SDKROOT}/Entitlements.plist"
substitutions: dictionary, variable substitutions
overrides: dictionary, values to add to the entitlements
Returns:
Path to the generated entitlements file.
"""
source_path = entitlements
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['PRODUCT_NAME'] + '.xcent')
if not source_path:
source_path = os.path.join(
os.environ['SDKROOT'],
'Entitlements.plist')
shutil.copy2(source_path, target_path)
data = self._LoadPlistMaybeBinary(target_path)
data = self._ExpandVariables(data, substitutions)
if overrides:
for key in overrides:
if key not in data:
data[key] = overrides[key]
plistlib.writePlist(data, target_path)
return target_path
def save_plist(data_dict, file_path):
"""
save a dict as a plist file
:param data_dict: dict data
:param file_path: plist file path to save
:return:
"""
import plistlib
if hasattr(plistlib, "dump"):
with open(file_path, 'wb') as fp:
plistlib.dump(data_dict, fp)
else:
plistlib.writePlist(data_dict, file_path)
def test_io(self):
pl = self._create()
plistlib.writePlist(pl, support.TESTFN)
pl2 = plistlib.readPlist(support.TESTFN)
self.assertEqual(dict(pl), dict(pl2))