Python plistlib.writePlist() Examples

The following are 30 code examples of plistlib.writePlist(). 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: __init__.py    From iOS-private-api-checker with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #2
Source File: __init__.py    From Alfred_SourceTree with MIT License 6 votes vote down vote up
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 
Example #3
Source File: shell.py    From collection with MIT License 6 votes vote down vote up
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
#---------------------------------------------------------------------- 
Example #4
Source File: macdist.py    From tensorlang with Apache License 2.0 6 votes vote down vote up
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() 
Example #5
Source File: AutoNBI.py    From autonbi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: buildlib.py    From stonix with GNU General Public License v2.0 6 votes vote down vote up
def modplist(self, targetFile, targetKey, newValue):
        '''Modify the value of a particular key in a Mac OS X property list file
        
        @author: Eric Ball

        :param targetFile: Path to the plist to be modified
        :param targetKey: The particular key within the plist to be modified
        :param newValue: The new value for the targetKey within the targetFile

        '''
        try:
            mypl = pl.readPlist(targetFile)
            mypl[targetKey] = newValue
            pl.writePlist(mypl, targetFile)
        except Exception:
            raise 
Example #7
Source File: jss_prefs.py    From python-jss with GNU General Public License v3.0 6 votes vote down vote up
def configure(self):
        """Prompt user for config and write to plist

        Uses preferences_file argument from JSSPrefs.__init__ as path
        to write.
        """
        prefs = {}
        print ("It seems like you do not have a preferences file configured. "
               "Please answer the following questions to generate a plist at "
               "%s for use with python-jss." % self.preferences_file)

        prefs["jss_url"] = raw_input(
            "The complete URL to your JSS, with port (e.g. "
            "'https://mycasperserver.org:8443')\nURL: ")

        prefs["jss_user"] = raw_input("API Username: ")
        prefs["jss_pass"] = getpass.getpass("API User's Password: ")
        verify_prompt = ("Do you want to verify that traffic is encrypted by "
                         "a certificate that you trust?: (Y|N) ")
        prefs["verify"] = loop_until_valid_response(verify_prompt)
        prefs["repos"] = self._handle_repos(prefs)

        plistlib.writePlist(prefs, self.preferences_file)
        print("Preferences created.\n") 
Example #8
Source File: mac_tool.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #9
Source File: kextupdater.py    From Lilu-and-Friends with MIT License 5 votes vote down vote up
def install(self):
        if os.path.exists(self.install_path):
            self.unload()
            self.uninstall()
        # Build the dict
        p = {
            "Label" : self.plist,
            "ProgramArguments" : [
                "/usr/bin/python",
                os.path.realpath(__file__)
            ],
            "RunAtLoad" : True
        }
        plistlib.writePlist(p, self.install_path)
        self.load() 
Example #10
Source File: tools.py    From recipe-robot with Apache License 2.0 5 votes vote down vote up
def write_report(report, report_file):
    FoundationPlist.writePlist(report, report_file) 
Example #11
Source File: test_plistlib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #12
Source File: mac_tool.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #13
Source File: mac_tool.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #14
Source File: mac_tool.py    From android-xmrig-miner with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #15
Source File: test_plistlib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #16
Source File: build.py    From WTFJH with GNU General Public License v3.0 5 votes vote down vote up
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") 
Example #17
Source File: phish.py    From rootOS with MIT License 5 votes vote down vote up
def edit_app_info(app_path, prompt):
    """edit app info"""
    plist = app_path + "/Contents/Info.plist"
    info = plistlib.readPlist(plist)
    info["CFBundleName"] = prompt
    info["CFBundleIdentifier"] = "com.apple.ScriptEditor.id." + \
        prompt.replace(" ", "")
    plistlib.writePlist(info, plist) 
Example #18
Source File: mac_tool.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #19
Source File: updater.py    From Lilu-and-Friends with MIT License 5 votes vote down vote up
def apply_min_sdk(self, version, temp):
        self.head("Updating Min SDK to {}".format(version))
        print(" ")
        if os.access(self.sdk_version_plist, os.W_OK):
            print("Have write permissions already...")
            # Can write to it normally
            print("Loading Info.plist...")
            # sdk_plist = plistlib.readPlist(self.sdk_version_plist)
            sdk_plist = self._get_plist_dict(self.sdk_version_plist)
            print("Updating MinimumSDKVersion...")
            sdk_plist["MinimumSDKVersion"] = version
            print("Flushing changes...")
            plistlib.writePlist(sdk_plist, self.sdk_version_plist)
            print("Done!")
            time.sleep(3)
            return
        print("No write permissions, using temp folder...")
        # Need to use a temp folder and then sudo it back
        self.r.run({"args":["cp", self.sdk_version_plist, temp], "stream" : True})
        print("Loading Info.plist...")
        # sdk_plist = plistlib.readPlist(os.path.join(temp, "Info.plist"))
        sdk_plist = self._get_plist_dict(os.path.join(temp, "Info.plist"))
        print("Updating MinimumSDKVersion...")
        sdk_plist["MinimumSDKVersion"] = version
        print("Writing Info.plist...")
        plistlib.writePlist(sdk_plist, os.path.join(temp, "Info.plist"))
        print("Copying back to {}...".format(self.sdk_version_plist))
        # Copy back over
        self.r.run({"args":["cp", os.path.join(temp, "Info.plist"), self.sdk_version_plist], "stream": True, "sudo" : True}) 
Example #20
Source File: package_app.py    From kivy-sdk-packager with MIT License 5 votes vote down vote up
def fill_meta(appname, arguments):
    print('Editing info.plist')
    bundleversion = arguments.get('--bundleversion')
    import plistlib
    info_plist = appname+'/Contents/info.plist'
    rootObject = plistlib.readPlist(info_plist)
    rootObject['NSHumanReadableCopyright'] = arguments.get('--author').decode('utf-8')
    rootObject['Bundle display name'] = arguments.get('--displayname')
    rootObject['Bundle identifier'] = arguments.get('--bundleid')
    rootObject['Bundle name'] = arguments.get('--bundlename')
    rootObject['Bundle version'] = arguments.get('--bundleversion')
    plistlib.writePlist(rootObject, info_plist) 
Example #21
Source File: mac_tool.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #22
Source File: mac_tool.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #23
Source File: conftest.py    From python-jss with GNU General Public License v3.0 5 votes vote down vote up
def jss_prefs_file(tmpdir):  # type: (str) -> str
    prefs_path = tmpdir.join('com.github.sheagcraig.python-jss.plist')
    plistlib.writePlist(JSS_PREFS, prefs_path)
    return prefs_path 
Example #24
Source File: test_plistlib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)) 
Example #25
Source File: test_plistlib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)) 
Example #26
Source File: test_plistlib.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)) 
Example #27
Source File: mac_tool.py    From StarsAndClown with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #28
Source File: mac_tool.py    From StarsAndClown with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #29
Source File: mac_tool.py    From gyp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #30
Source File: better-jamf-policy-deferral.py    From better-jamf-policy-deferral with GNU General Public License v3.0 5 votes vote down vote up
def write_launchdaemon(job_definition, path):
    """Writes the passed job definition to a LaunchDaemon"""

    success = True

    try:
        with open(path, 'w+') as output_file:
            plistlib.writePlist(job_definition, output_file)
    except IOError:
        print "Unable to write LaunchDaemon!"
        success = False

    # Permissions and ownership
    try:
        os.chmod(path, 0644)
    except:
        print "Unable to set permissions on LaunchDaemon!"
        success = False

    try:
        os.chown(path, 0, 0)
    except:
        print "Unable to set ownership on LaunchDaemon!"
        success = False

    # Load job
    load_job = subprocess.Popen(['launchctl', 'load', path],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    load_job.communicate()

    if load_job.returncode > 0:
        print "Unable to load LaunchDaemon!"
        success = False

    return success