Python plistlib.load() Examples

The following are 30 code examples of plistlib.load(). 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: forms.py    From zentral with Apache License 2.0 6 votes vote down vote up
def clean(self):
        source_file = self.cleaned_data.get("source_file")
        if source_file:
            try:
                source = plistlib.load(source_file)
            except Exception:
                raise forms.ValidationError("This file is not a plist.")
            self.cleaned_data["source"] = source
            try:
                self.cleaned_data["source_payload_identifier"] = source["PayloadIdentifier"]
            except KeyError:
                raise forms.ValidationError("Missing PayloadIdentifier")

            for source_key, obj_key in (("PayloadDisplayName", "payload_display_name"),
                                        ("PayloadDescription", "payload_description")):
                self.cleaned_data[obj_key] = source.get(source_key) or ""
            return self.cleaned_data 
Example #2
Source File: test_plistlib.py    From android_universal with MIT License 6 votes vote down vote up
def test_keysort_bytesio(self):
        pl = collections.OrderedDict()
        pl['b'] = 1
        pl['a'] = 2
        pl['c'] = 3

        for fmt in ALL_FORMATS:
            for sort_keys in (False, True):
                with self.subTest(fmt=fmt, sort_keys=sort_keys):
                    b = BytesIO()

                    plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
                    pl2 = plistlib.load(BytesIO(b.getvalue()),
                        dict_type=collections.OrderedDict)

                    self.assertEqual(dict(pl), dict(pl2))
                    if sort_keys:
                        self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
                    else:
                        self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) 
Example #3
Source File: platform.py    From android_universal with MIT License 6 votes vote down vote up
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

    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
    release = pl['ProductVersion']
    versioninfo = ('', '', '')
    machine = os.uname().machine
    if machine in ('ppc', 'Power Macintosh'):
        # Canonical name
        machine = 'PowerPC'

    return release, versioninfo, machine 
Example #4
Source File: confaccts.py    From iLEAPP with MIT License 6 votes vote down vote up
def get_confaccts(files_found, report_folder, seeker):
    data_list = []
    file_found = str(files_found[0])
    with open(file_found, "rb") as fp:
        pl = plistlib.load(fp)
        for key, val in pl.items():
            data_list.append((key, val))
    
    report = ArtifactHtmlReport('Account Configuration')
    report.start_artifact_report(report_folder, 'Account Configuration')
    report.add_script()
    data_headers = ('Key','Values' )     
    report.write_artifact_data_table(data_headers, data_list, file_found)
    report.end_artifact_report()
    
    tsvname = 'Account Configuration'
    tsv(report_folder, data_headers, data_list, tsvname) 
Example #5
Source File: plist.py    From appleloops with Apache License 2.0 6 votes vote down vote up
def readPlist(plist_path):
    """A wrapper function to read property list files with either Python 2 or Python 3 versions.
    If the file is a binary file, and the Python version is 2.7+, the file is converted using 'plutil'."""
    result = None

    # Python 3.4.0+ deprecates the old '.readPlist*' methods.
    if LooseVersion(version.PYTHON_VER) > LooseVersion('3.4.0'):
        with open(plist_path, 'rb') as plistfile:
            # pylint: disable=no-member
            result = plistlib.load(plistfile)
            # pylint: enable=no-member
    elif version.in_version_range('2.7.0', version.PYTHON_VER, '3.3.99'):
        if is_binary(plist_path):
            plist_str = convert(plist_path)
            result = plistlib.readPlistFromString(plist_str)
        else:
            result = plistlib.readPlist(plist_path)

    return result 
Example #6
Source File: main.py    From TreeNote with GNU General Public License v3.0 6 votes vote down vote up
def start():
    app = QApplication(sys.argv)
    app.setApplicationName('TreeNote')
    app.setOrganizationName('Jan Korte')
    app.setWindowIcon(QIcon(':/logo'))
    QFontDatabase.addApplicationFont(os.path.join(RESOURCE_FOLDER, 'SourceSansPro-Regular.otf'))

    locale = QLocale.system().name()
    qt_translator = QTranslator()
    if qt_translator.load("qtbase_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
        app.installTranslator(qt_translator)
    app_translator = QTranslator()
    if app_translator.load('treenote_' + locale, os.path.join(RESOURCE_FOLDER, 'locales')):
        app.installTranslator(app_translator)

    form = MainWindow(app)
    form.show()
    app.exec_() 
Example #7
Source File: test_plistlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_keysort_bytesio(self):
        pl = collections.OrderedDict()
        pl['b'] = 1
        pl['a'] = 2
        pl['c'] = 3

        for fmt in ALL_FORMATS:
            for sort_keys in (False, True):
                with self.subTest(fmt=fmt, sort_keys=sort_keys):
                    b = BytesIO()

                    plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
                    pl2 = plistlib.load(BytesIO(b.getvalue()),
                        dict_type=collections.OrderedDict)

                    self.assertEqual(dict(pl), dict(pl2))
                    if sort_keys:
                        self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
                    else:
                        self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) 
Example #8
Source File: platform.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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

    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
    release = pl['ProductVersion']
    versioninfo = ('', '', '')
    machine = os.uname().machine
    if machine in ('ppc', 'Power Macintosh'):
        # Canonical name
        machine = 'PowerPC'

    return release, versioninfo, machine 
Example #9
Source File: updater.py    From Lilu-and-Friends with MIT License 6 votes vote down vote up
def _get_plist_dict(self, path):
        # Returns a dict of the plist data as a dict
        if not os.path.exists(path):
            print("{} doesn't exist!".format(path))
            return None
        try:
            if sys.version_info >= (3, 0):
                with open(path, 'rb') as p:
                    d = plistlib.load(p)
            else:
                p_string = self._get_output(["plutil", "-convert", "json", "-o", "-", "--", path ])[0]
                d = json.loads(p_string)
        except Exception as e:
            print(str(e))
            return None
        return d 
Example #10
Source File: macappfinder.py    From galaxy-integration-humblebundle with GNU General Public License v3.0 6 votes vote down vote up
def __parse_bundle(app_dir: os.PathLike) -> Optional[pathlib.Path]:
        dir_ = pathlib.Path(app_dir).resolve()
        try:
            with open(dir_ / 'Contents' / 'Info.plist', 'rb') as f:
                plist: Dict[str, str] = plistlib.load(f)
        except (FileExistsError, OSError) as e:
            logging.error(f'{repr(e)}')
            return None
        try:
            exe_name = plist['CFBundleExecutable']
        except KeyError as e:
            logging.error(f'No Executable in Info.plist: {repr(e)}')
            return None
        try:
            name = plist.get('CFBundleDisplayName', plist['CFBundleName'])
        except KeyError:
            name = pathlib.PurePath(app_dir).stem
        bundle = BundleInfo(dir_, exe_name, name)
        return bundle.executable 
Example #11
Source File: test_plistlib.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_keysort_bytesio(self):
        pl = collections.OrderedDict()
        pl['b'] = 1
        pl['a'] = 2
        pl['c'] = 3

        for fmt in ALL_FORMATS:
            for sort_keys in (False, True):
                with self.subTest(fmt=fmt, sort_keys=sort_keys):
                    b = BytesIO()

                    plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
                    pl2 = plistlib.load(BytesIO(b.getvalue()),
                        dict_type=collections.OrderedDict)

                    self.assertEqual(dict(pl), dict(pl2))
                    if sort_keys:
                        self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
                    else:
                        self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) 
Example #12
Source File: platform.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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

    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
    release = pl['ProductVersion']
    versioninfo = ('', '', '')
    machine = os.uname().machine
    if machine in ('ppc', 'Power Macintosh'):
        # Canonical name
        machine = 'PowerPC'

    return release, versioninfo, machine 
Example #13
Source File: platform.py    From Imogen with MIT License 6 votes vote down vote up
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

    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
    release = pl['ProductVersion']
    versioninfo = ('', '', '')
    machine = os.uname().machine
    if machine in ('ppc', 'Power Macintosh'):
        # Canonical name
        machine = 'PowerPC'

    return release, versioninfo, machine 
Example #14
Source File: test_plistlib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_keysort_bytesio(self):
        pl = collections.OrderedDict()
        pl['b'] = 1
        pl['a'] = 2
        pl['c'] = 3

        for fmt in ALL_FORMATS:
            for sort_keys in (False, True):
                with self.subTest(fmt=fmt, sort_keys=sort_keys):
                    b = BytesIO()

                    plistlib.dump(pl, b, fmt=fmt, sort_keys=sort_keys)
                    pl2 = plistlib.load(BytesIO(b.getvalue()),
                        dict_type=collections.OrderedDict)

                    self.assertEqual(dict(pl), dict(pl2))
                    if sort_keys:
                        self.assertEqual(list(pl2.keys()), ['a', 'b', 'c'])
                    else:
                        self.assertEqual(list(pl2.keys()), ['b', 'a', 'c']) 
Example #15
Source File: plist.py    From thinkpad-x1c5-hackintosh with MIT License 6 votes vote down vote up
def load(fp, fmt=None, use_builtin_types=None, dict_type=dict):
    if _check_py3():
        use_builtin_types = True if use_builtin_types == None else use_builtin_types
        return plistlib.load(fp, fmt=fmt, use_builtin_types=use_builtin_types, dict_type=dict_type)
    elif not _is_binary(fp):
        # We monkey patch the begin_dict function to allow for other
        # dict types
        p = plistlib.PlistParser()
        def begin_dict(attrs):
            d = dict_type()
            p.addObject(d)
            p.stack.append(d)
        p.begin_dict = begin_dict
        root = p.parse(fp)
        return root
    else:
        use_builtin_types = False if use_builtin_types == None else use_builtin_types
        p = _BinaryPlistParser(use_builtin_types=use_builtin_types, dict_type=dict_type)
        return p.parse(fp) 
Example #16
Source File: utils.py    From osxphotos with MIT License 6 votes vote down vote up
def get_system_library_path():
    """ return the path to the system Photos library as string """
    """ only works on MacOS 10.15 """
    """ on earlier versions, returns None """
    _, major, _ = _get_os_version()
    if int(major) < 15:
        logging.debug(
            f"get_system_library_path not implemented for MacOS < 10.15: you have {major}"
        )
        return None

    plist_file = pathlib.Path(
        str(pathlib.Path.home())
        + "/Library/Containers/com.apple.photolibraryd/Data/Library/Preferences/com.apple.photolibraryd.plist"
    )
    if plist_file.is_file():
        with open(plist_file, "rb") as fp:
            pl = plistload(fp)
    else:
        logging.debug(f"could not find plist file: {str(plist_file)}")
        return None

    return pl.get("SystemLibraryPath") 
Example #17
Source File: platform.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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

    with open(fn, 'rb') as f:
        pl = plistlib.load(f)
    release = pl['ProductVersion']
    versioninfo = ('', '', '')
    machine = os.uname().machine
    if machine in ('ppc', 'Power Macintosh'):
        # Canonical name
        machine = 'PowerPC'

    return release, versioninfo, machine 
Example #18
Source File: plistinfo.py    From macbuild-ansible with MIT License 6 votes vote down vote up
def main():
    try:
        try:
            plist_file = determine_plist_path(sys.argv[1])
            with open(plist_file, 'rb') as f:
                plist_data = plistlib.load(f)
        except IndexError:
            plist_file = '<stdin>'
            plist_data = plistlib.loads(sys.stdin.buffer.read())

        print(yaml.dump(plist_data, default_flow_style=False), end='')
    except IOError:
        print(f'{RED}Error: The requested plist file {plist_file} was not found{ENDC}')
        exit(1)
    except plistlib.InvalidFileException:
        print(f'{RED}Error: Unable to parse the requested plist file {plist_file}{ENDC}')
        exit(1)
    except KeyboardInterrupt:
        pass 
Example #19
Source File: celWireless.py    From iLEAPP with MIT License 5 votes vote down vote up
def get_celWireless(files_found, report_folder, seeker):
    data_list = []
    for filepath in files_found:
        basename = os.path.basename(filepath)
        if (
            basename == "com.apple.commcenter.device_specific_nobackup.plist"
            or basename == "com.apple.commcenter.plist"
        ):
            p = open(filepath, "rb")
            plist = plistlib.load(p)
            for key, val in plist.items():
                data_list.append((key, val, filepath))
                if key == "ReportedPhoneNumber":
                    logdevinfo(f"Reported Phone Number: {val}")
                
                if key == "CDMANetworkPhoneNumberICCID":
                    logdevinfo(f"CDMA Network Phone Number ICCID: {val}")
                
                if key == "imei":
                    logdevinfo(f"IMEI: {val}")
                    
                if key == "LastKnownICCID":
                    logdevinfo(f"Last Known ICCID: {val}")
                
                if key == "meid":
                    logdevinfo(f"MEID: {val}")
    
    
    
    location = 'see source field'
    report = ArtifactHtmlReport('Cellular Wireless')
    report.start_artifact_report(report_folder, 'Cellular Wireless')
    report.add_script()
    data_headers = ('Key','Values', 'Source' )     
    report.write_artifact_data_table(data_headers, data_list, location)
    report.end_artifact_report()
    
    tsvname = 'Cellular Wireless'
    tsv(report_folder, data_headers, data_list, tsvname) 
Example #20
Source File: test_plistlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_io(self):
        pl = self._create()
        with open(support.TESTFN, 'wb') as fp:
            plistlib.dump(pl, fp)

        with open(support.TESTFN, 'rb') as fp:
            pl2 = plistlib.load(fp)

        self.assertEqual(dict(pl), dict(pl2))

        self.assertRaises(AttributeError, plistlib.dump, pl, 'filename')
        self.assertRaises(AttributeError, plistlib.load, 'filename') 
Example #21
Source File: test_plistlib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_bytesio(self):
        for fmt in ALL_FORMATS:
            with self.subTest(fmt=fmt):
                b = BytesIO()
                pl = self._create(fmt=fmt)
                plistlib.dump(pl, b, fmt=fmt)
                pl2 = plistlib.load(BytesIO(b.getvalue()), fmt=fmt)
                self.assertEqual(dict(pl), dict(pl2))
                pl2 = plistlib.load(BytesIO(b.getvalue()))
                self.assertEqual(dict(pl), dict(pl2)) 
Example #22
Source File: plist.py    From thinkpad-x1c5-hackintosh with MIT License 5 votes vote down vote up
def readPlist(pathOrFile):
    if not isinstance(pathOrFile, _get_inst()):
        return load(pathOrFile)
    with open(pathOrFile, "rb") as f:
        return load(f) 
Example #23
Source File: __init__.py    From pymobiledevice with GNU General Public License v3.0 5 votes vote down vote up
def load_pickle(filename):
    f = gzip.open(filename,"rb")
    data = cPickle.load(f)
    f.close()
    return data 
Example #24
Source File: main.py    From TreeNote with GNU General Public License v3.0 5 votes vote down vote up
def open_file(self, open_path):
        self.item_model.selected_item, self.item_model.rootItem, self.bookmark_model.rootItem = pickle.load(
            open(open_path, 'rb'))
        self.save_path = open_path
        self.change_active_tree() 
Example #25
Source File: plist.py    From macbuild-ansible with MIT License 5 votes vote down vote up
def do_plist(module, filename, values, backup=False):
    working_values = values
    changed = False

    try:
        f = open(filename, 'rb')
        plist = plistlib.load(f)
    except IOError:
        plist = {}
    except plistlib.InvalidFileException:
        module.fail_json(msg="an invalid plist already exists")

    changed = not equal(plist, working_values)

    if changed and not module.check_mode:
        if backup:
            module.backup_local(filename)

        try:
            update(plist, working_values)
            plist_dir = os.path.dirname(filename)
            if not os.path.exists(plist_dir):
                os.makedirs(plist_dir)
            f = open(filename, 'wb')
            plistlib.dump(plist, f)
        except Exception as e:
            module.fail_json(msg="Can't change %s" % filename, error=str(e))

    return changed 
Example #26
Source File: dhcpl.py    From iLEAPP with MIT License 5 votes vote down vote up
def get_dhcpl(files_found, report_folder, seeker):
    file_found = str(files_found[0])
    data_list = []
    with open(file_found, "rb") as fp:
        pl = plistlib.load(fp)
        for key, val in pl.items():
            if key == "IPAddress":
                data_list.append((key,val))
            if key == "LeaseLength":
                data_list.append((key,val))
            if key == "LeaseStartDate":
                data_list.append((key,val))
            if key == "RouterHardwareAddress":
                data_list.append((key,val))
            if key == "RouterIPAddress":
                data_list.append((key,val))
            if key == "SSID":
                data_list.append((key,val))
    
    if len(data_list) > 0:
        report = ArtifactHtmlReport('DHCP Received List')
        report.start_artifact_report(report_folder, 'Received List')
        report.add_script()
        data_headers = ('Key', 'Value')   
        report.write_artifact_data_table(data_headers, data_list, file_found)
        report.end_artifact_report()
        
        tsvname = 'DHCP Received List'
        tsv(report_folder, data_headers, data_list, tsvname)
    else:
        logfunc('No data available')
    return 
Example #27
Source File: launch.py    From cwl-airflow with Apache License 2.0 5 votes vote down vote up
def load(self):
        subprocess.run(["launchctl", "load", "-w", os.path.expanduser(self.__AIRFLOW_SCH)])
        subprocess.run(["launchctl", "load", "-w", os.path.expanduser(self.__AIRFLOW_WEB)])
        subprocess.run(["launchctl", "load", "-w", os.path.expanduser(self.__AIRFLOW_API)]) 
Example #28
Source File: dataArk.py    From iLEAPP with MIT License 5 votes vote down vote up
def get_dataArk(files_found, report_folder, seeker):
    data_list = []
    file_found = str(files_found[0])
    with open(file_found, "rb") as fp:
        pl = plistlib.load(fp)
        for key, val in pl.items():
            data_list.append((key, val))
            
            if key == "-DeviceName":
                logdevinfo(f"Device name: {val}")
            if key == "-TimeZone":
                logdevinfo(f"Timezone per Data Ark: {val}")
            if key == "com.apple.iTunes.backup-LastBackupComputerName":
                logdevinfo(f"Last backup computer name: {val}")
            if key == ("com.apple.iTunes.backup-LastBackupComputerType"):
                logdevinfo(f"Last backup computer type: {val}")
  
    report = ArtifactHtmlReport('Data Ark')
    report.start_artifact_report(report_folder, 'Data Ark')
    report.add_script()
    data_headers = ('Key','Values' )     
    report.write_artifact_data_table(data_headers, data_list, file_found)
    report.end_artifact_report()
    
    tsvname = 'Data Ark'
    tsv(report_folder, data_headers, data_list, tsvname) 
Example #29
Source File: iconsScreen.py    From iLEAPP with MIT License 5 votes vote down vote up
def get_iconsScreen(files_found, report_folder, seeker):
    data_list = []
    data_pre_list = []
    file_found = str(files_found[0])
    with open(file_found, "rb") as fp:
        plist = plistlib.load(fp)
        for key, val in plist.items():
            if key == "buttonBar":
                bbar = val
            elif key == "iconLists":
                icon = val

        for x in range(0, len(icon)):
            page = icon[x]
            htmlstring = (f"<table><tr>")
            htmlstring = htmlstring + (f'<td colspan="4"> Icons screen #{x}</td>')
            for y in range(0, len(page)):
                rows = page[y]
                if (y == 0) or (y % 4 == 0):
                    htmlstring = htmlstring + ("</tr><tr>")
                htmlstring = htmlstring + (f"<td width = 25%>{rows}</td>")
            htmlstring = htmlstring + ("</tr></table>")
            data_list.append((htmlstring,))

        htmlstring = ''
        htmlstring = (f'<table><tr> <td colspan="4"> Icons bottom bar</td></tr><tr>')
        for x in range(0, len(bbar)):
            htmlstring = htmlstring +(f"<td width = 25%>{bbar[x]}</td>")
        htmlstring = htmlstring +("</tr></table>")
        data_list.append((htmlstring,))

        logfunc("Screens: " + str(len(icon)))

        report = ArtifactHtmlReport(f'Apps per screen')
        report.start_artifact_report(report_folder, f'Apps per screen')
        report.add_script()
        data_headers = ((f'Apps per Screens',))     
        report.write_artifact_data_table(data_headers, data_list, file_found, html_escape=False)
        report.end_artifact_report() 
Example #30
Source File: utils.py    From restatic with GNU General Public License v3.0 5 votes vote down vote up
def get_sorted_wifis(profile):
    """Get SSIDs from OS and merge with settings in DB."""

    if sys.platform == "darwin":
        plist_path = "/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist"
        plist_file = open(plist_path, "rb")
        wifis = plistlib.load(plist_file)["KnownNetworks"]
        if wifis:
            for wifi in wifis.values():
                timestamp = wifi.get("LastConnected", None)
                ssid = wifi["SSIDString"]
                db_wifi, created = WifiSettingModel.get_or_create(
                    ssid=ssid,
                    profile=profile.id,
                    defaults={"last_connected": timestamp, "allowed": True},
                )

                # update last connected time
                if not created and db_wifi.last_connected != timestamp:
                    db_wifi.last_connected = timestamp
                    db_wifi.save()

        # remove Wifis that were deleted in the system.
        deleted_wifis = WifiSettingModel.select().where(
            WifiSettingModel.ssid.not_in([w["SSIDString"] for w in wifis.values()])
        )
        for wifi in deleted_wifis:
            wifi.delete_instance()

    return (
        WifiSettingModel.select()
        .where(WifiSettingModel.profile == profile.id)
        .order_by(-WifiSettingModel.last_connected)
    )