def do_transaction():
'''Wrapping method.
Try just transaction A; if that fails, then enroll and
then do transaction A again.'''
enrollment_required = False
enrollment_completed = False
transaction_a_result_dict = do_transaction_only()
if not transaction_a_result_dict['result']:
enrollment_required = True
enrollment_completed = enroll_only()
transaction_a_result_dict = do_transaction_only()
# Add enrollment_status dict to transaction A dict:
transaction_a_result_dict['enrollment_status'] = {"required":enrollment_required,
"completed":enrollment_completed,
"result":(not enrollment_required) or enrollment_completed}
transaction_a_result_dict['transaction_completed_date'] = datetime.utcnow()
# Write result:
plistlib.writePlist(transaction_a_result_dict, config_paths.RESULT_TRANSACTION_A_FILE_PATH)
python类writePlist()的实例源码
def make_plist(self, version=None):
"""
?????????????Info.plist?????
"""
info = {
'CFBundleDisplayName': DISPLAY_NAME,
'CFBundleExecutable': EXECUTABLE_NAME,
'CFBundleIconFile': ICON_FILE_NAME,
'CFBundleIdentifier': self.bundle_identifier,
'CFBundleInfoDictionaryVersion': '6.0',
'CFBundleLocalizations': list(LOCALIZED_BUNDLE_NAMES.keys()),
'CFBundleName': self.bundle_name,
'CFBundlePackageType': 'APPL',
'CFBundleShortVersionString': '1',
'CFBundleSignature': '???',
'CFBundleVersion': '1',
'LSHasLocalizedDisplayName': True,
}
if version:
info['CFBundleShortVersionString'] = version
path = os.path.join(self.contents_dir, 'Info.plist')
plistlib.writePlist(info, path)
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 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 writePlist(rootObject, pathOrFile, binary=True):
if not binary:
rootObject = wrapDataObject(rootObject, binary)
if hasattr(plistlib, "dump"):
if isinstance(pathOrFile, (bytes, unicode)):
with open(pathOrFile, 'wb') as f:
return plistlib.dump(rootObject, f)
else:
return plistlib.dump(rootObject, pathOrFile)
else:
return plistlib.writePlist(rootObject, pathOrFile)
else:
didOpen = False
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'wb')
didOpen = True
writer = PlistWriter(pathOrFile)
result = writer.writeRoot(rootObject)
if didOpen:
pathOrFile.close()
return result
def writePlist(rootObject, pathOrFile, binary=True):
if not binary:
rootObject = wrapDataObject(rootObject, binary)
if hasattr(plistlib, "dump"):
if isinstance(pathOrFile, (bytes, unicode)):
with open(pathOrFile, 'wb') as f:
return plistlib.dump(rootObject, f)
else:
return plistlib.dump(rootObject, pathOrFile)
else:
return plistlib.writePlist(rootObject, pathOrFile)
else:
didOpen = False
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'wb')
didOpen = True
writer = PlistWriter(pathOrFile)
result = writer.writeRoot(rootObject)
if didOpen:
pathOrFile.close()
return result
def writePlist(rootObject, pathOrFile, binary=True):
if not binary:
rootObject = wrapDataObject(rootObject, binary)
if hasattr(plistlib, "dump"):
if isinstance(pathOrFile, (bytes, unicode)):
with open(pathOrFile, 'wb') as f:
return plistlib.dump(rootObject, f)
else:
return plistlib.dump(rootObject, pathOrFile)
else:
return plistlib.writePlist(rootObject, pathOrFile)
else:
didOpen = False
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'wb')
didOpen = True
writer = PlistWriter(pathOrFile)
result = writer.writeRoot(rootObject)
if didOpen:
pathOrFile.close()
return result
def plist_save(filename, data, binary = False):
import plistlib
if not binary:
plistlib.writePlist(data, filename)
return 0
import warnings
warnings.filterwarnings("ignore")
tmpname = os.tempnam(None, 'plist.')
plistlib.writePlist(data, tmpname)
plutil('-convert', 'binary1', '-o', filename, tmpname)
os.remove(tmpname)
return 0
#----------------------------------------------------------------------
# testing case
#----------------------------------------------------------------------
def create_plist(self):
"""Create the Contents/Info.plist file"""
# Use custom plist if supplied, otherwise create a simple default.
if self.custom_info_plist:
contents = plistlib.readPlist(self.custom_info_plist)
else:
contents = {
'CFBundleIconFile': 'icon.icns',
'CFBundleDevelopmentRegion': 'English',
}
# Ensure CFBundleExecutable is set correctly
contents['CFBundleExecutable'] = self.bundle_executable
plist = open(os.path.join(self.contentsDir, 'Info.plist'), 'wb')
plistlib.writePlist(contents, plist)
plist.close()
def create_plist(self):
"""Create the Contents/Info.plist file"""
import plistlib
contents = {
'CFBundleName': 'BigBrotherBot (B3) %s' % b3_version,
'CFBundleGetInfoString': b3_version,
'CFBundleShortVersionString': b3_version,
'CFBundleVersion': b3_version,
'CFBundlePackageType': 'APPL',
'CFBundleIconFile': 'icon.icns',
'CFBundleIdentifier': 'net.bigbrotherbot.www',
'CFBundleInfoDictionaryVersion': '6.0',
'CFBundleDevelopmentRegion': 'English',
'CFBundleSpokenName': 'Big Brother Bot (B3)',
'CFBundleExecutable': self.bundle_executable
}
plist = open(os.path.join(self.contentsDir, 'Info.plist'), 'wb')
plistlib.writePlist(contents, plist)
plist.close()
def main():
client_manifest_path = (
"/Library/Managed Installs/manifests/client_manifest.plist")
if os.path.exists(client_manifest_path):
client_manifest = plistlib.readPlist(client_manifest_path)
else:
client_manifest = {}
formatted_results = {
"plugin": "Manifests",
"historical": False,
"data": {"included_manifests": "+".join(
client_manifest.get("included_manifests", []))}}
if os.path.exists(RESULTS_PATH):
plugin_results = plistlib.readPlist(RESULTS_PATH)
else:
plugin_results = []
plugin_results.append(formatted_results)
plistlib.writePlist(plugin_results, RESULTS_PATH)
def main():
client_manifest_path = (
"/Library/Managed Installs/manifests/client_manifest.plist")
if os.path.exists(client_manifest_path):
client_manifest = plistlib.readPlist(client_manifest_path)
else:
client_manifest = {}
formatted_results = {
"plugin": "Catalogs",
"historical": False,
"data": {"Catalogs": "+".join(client_manifest.get("catalogs", []))}}
if os.path.exists(RESULTS_PATH):
plugin_results = plistlib.readPlist(RESULTS_PATH)
else:
plugin_results = []
plugin_results.append(formatted_results)
plistlib.writePlist(plugin_results, RESULTS_PATH)
def main():
translator = Translator()
fileName=os.path.expanduser('Preferences.strings')
if os.path.exists(fileName):
pl=plistlib.readPlist(fileName)
lst = []
for key in pl:
val = pl[key]
print('key: %s, val: %s' % (key, val))
translation = translator.translate(val, dest='ru')
pl[key]=translation.text
print('translation: %s' % (pl[key]))
plistlib.writePlist(pl, 'Preferences_ru.strings')
else:
print( '%s does not exist, so can\'t be read' % fileName)
def prepworkdir(workdir):
"""Copies in the required Apple-provided createCommon.sh and also creates
an empty file named createVariables.sh. We actually pass the variables
this file might contain using environment variables but it is expected
to be present so we fake out Apple's createNetInstall.sh script."""
commonsource = os.path.join(BUILDEXECPATH, 'createCommon.sh')
commontarget = os.path.join(workdir, 'createCommon.sh')
shutil.copyfile(commonsource, commontarget)
open(os.path.join(workdir, 'createVariables.sh'), 'a').close()
if isHighSierra:
enterprisedict = {}
enterprisedict['SIU-SIP-setting'] = True
enterprisedict['SIU-SKEL-setting'] = False
enterprisedict['SIU-teamIDs-to-add'] = []
plistlib.writePlist(enterprisedict, os.path.join(workdir, '.SIUSettings'))
# Example usage of the function:
# decompress('PayloadJava.cpio.xz', 'PayloadJava.cpio')
# Decompresses a xz compressed file from the first input file path to the second output file path
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 WriteTo(self, target_path):
plistlib.writePlist(self._data, target_path)
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 generate_buildinfo_plist(launchdinfo, pkg_directory):
"""Generate pkg build-info.plist"""
buildinfo = {
'postinstall_action': 'none',
'name': launchdinfo['pkgname'],
'distribution_style': False,
'install_location': '/',
'version': launchdinfo['version'],
'identifier': launchdinfo['pkgid']
}
output = os.path.join(pkg_directory, 'build-info.plist')
plistlib.writePlist(buildinfo, output)
def save_format_xml(self, file_name=None):
"""Saves in old (xml) format"""
if not file_name:
file_name = self.pbxproj_path
# This code is adapted from plistlib.writePlist
with open(file_name, "w") as f:
writer = PBXWriter(f)
writer.writeln("<plist version=\"1.0\">")
writer.writeValue(self.data)
writer.writeln("</plist>")
def save(self):
if self.plist is not None:
plistlib.writePlist(self.plist, self.filename)
def renameUFOKerning(ufoPath, newNames, dryRun=False, print=print):
filename = os.path.join(ufoPath, 'kerning.plist')
plist = None
try:
plist = plistlib.readPlist(filename)
except:
return
didChange = False
newPlist = {}
for leftName, right in plist.items():
if leftName in newNames:
didChange = True
leftName = newNames[leftName]
newRight = {}
for rightName, kernValue in plist.items():
if rightName in newNames:
didChange = True
rightName = newNames[rightName]
newRight[rightName] = kernValue
newPlist[leftName] = right
if didChange:
print('Writing', filename)
if not dryRun:
plistlib.writePlist(newPlist, filename)
def fixupGroups(fontPath, dstGlyphNames, srcToDstMap, dryRun, stats):
filename = os.path.join(fontPath, 'groups.plist')
groups = plistlib.readPlist(filename)
groups2 = {}
glyphToGroups = {}
for groupName, glyphNames in groups.iteritems():
glyphNames2 = []
for glyphName in glyphNames:
if glyphName in srcToDstMap:
gn2 = srcToDstMap[glyphName]
stats.renamedGlyphs[glyphName] = gn2
glyphName = gn2
if glyphName in dstGlyphNames:
glyphNames2.append(glyphName)
glyphToGroups[glyphName] = glyphToGroups.get(glyphName, []) + [groupName]
else:
stats.removedGlyphs.add(glyphName)
if len(glyphNames2) > 0:
groups2[groupName] = glyphNames2
else:
stats.removedGroups.add(groupName)
print('Writing', filename)
if not dryRun:
plistlib.writePlist(groups2, filename)
return groups2, glyphToGroups
def WriteTo(self, target_path):
plistlib.writePlist(self._data, target_path)
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 create_plist(self):
BOOK_EXTENSIONS = calibre_constants['book_extensions']
env = dict(**ENV)
env['CALIBRE_LAUNCHED_FROM_BUNDLE'] = '1'
docs = [{'CFBundleTypeName': 'E-book',
'CFBundleTypeExtensions': list(BOOK_EXTENSIONS),
'CFBundleTypeIconFile': 'book.icns',
'CFBundleTypeRole': 'Viewer',
}]
pl = dict(
CFBundleDevelopmentRegion='English',
CFBundleDisplayName=APPNAME,
CFBundleName=APPNAME,
CFBundleIdentifier='net.kovidgoyal.calibre',
CFBundleVersion=VERSION,
CFBundleShortVersionString=VERSION,
CFBundlePackageType='APPL',
CFBundleSignature='????',
CFBundleExecutable='calibre',
CFBundleDocumentTypes=docs,
LSMinimumSystemVersion='10.9.5',
LSRequiresNativeExecution=True,
NSAppleScriptEnabled=False,
NSHumanReadableCopyright=time.strftime('Copyright %Y, Kovid Goyal'),
CFBundleGetInfoString=('calibre, an E-book management '
'application. Visit https://calibre-ebook.com for details.'),
CFBundleIconFile='calibre.icns',
NSHighResolutionCapable=True,
LSApplicationCategoryType='public.app-category.productivity',
LSEnvironment=env
)
plistlib.writePlist(pl, join(self.contents_dir, 'Info.plist'))
def test_io(self):
pl = self._create()
plistlib.writePlist(pl, support.TESTFN)
pl2 = plistlib.readPlist(support.TESTFN)
self.assertEqual(dict(pl), dict(pl2))
def test_bytesio(self):
from io import BytesIO
b = BytesIO()
pl = self._create()
plistlib.writePlist(pl, b)
pl2 = plistlib.readPlist(BytesIO(b.getvalue()))
self.assertEqual(dict(pl), dict(pl2))
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