当前位置: 首页>>代码示例>>Python>>正文


Python plistlib.load方法代码示例

本文整理汇总了Python中plistlib.load方法的典型用法代码示例。如果您正苦于以下问题:Python plistlib.load方法的具体用法?Python plistlib.load怎么用?Python plistlib.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在plistlib的用法示例。


在下文中一共展示了plistlib.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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) 
开发者ID:B0hrer,项目名称:thinkpad-x1c5-hackintosh,代码行数:21,代码来源:plist.py

示例2: main

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:fgimian,项目名称:macbuild-ansible,代码行数:21,代码来源:plistinfo.py

示例3: get_system_library_path

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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") 
开发者ID:RhetTbull,项目名称:osxphotos,代码行数:25,代码来源:utils.py

示例4: _mac_ver_xml

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:platform.py

示例5: test_keysort_bytesio

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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']) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_plistlib.py

示例6: clean

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:zentralopensource,项目名称:zentral,代码行数:19,代码来源:forms.py

示例7: __parse_bundle

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:UncleGoogle,项目名称:galaxy-integration-humblebundle,代码行数:21,代码来源:macappfinder.py

示例8: _get_plist_dict

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:corpnewt,项目名称:Lilu-and-Friends,代码行数:18,代码来源:updater.py

示例9: start

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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_() 
开发者ID:TreeNote,项目名称:TreeNote,代码行数:20,代码来源:main.py

示例10: readPlist

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:carlashley,项目名称:appleloops,代码行数:21,代码来源:plist.py

示例11: get_confaccts

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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) 
开发者ID:abrignoni,项目名称:iLEAPP,代码行数:19,代码来源:confaccts.py

示例12: get_dict_from_recipe_name

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
def get_dict_from_recipe_name(recipe_name):
        recipes_directory = os.path.normpath(os.path.dirname(__file__) + "/../recipe/") + "/"

        # We get the required recipe
        recipe_path = recipes_directory + recipe_name

        # We get is as dict
        recipe_dict = plistlib.load(open(recipe_path, 'rb'), fmt=plistlib.FMT_XML)

        return recipe_dict 
开发者ID:OpenMDM,项目名称:OpenMDM,代码行数:12,代码来源:models.py

示例13: patch_mac_app

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
def patch_mac_app():
    """Patch .app to use our Info.plist and save some space."""
    app_path = os.path.join('dist', 'qutebrowser.app')

    # Patch Info.plist - pyinstaller's options are too limiting
    plist_path = os.path.join(app_path, 'Contents', 'Info.plist')
    with open(plist_path, "rb") as f:
        plist_data = plistlib.load(f)
    plist_data.update(INFO_PLIST_UPDATES)
    with open(plist_path, "wb") as f:
        plistlib.dump(plist_data, f)

    # Replace some duplicate files by symlinks
    framework_path = os.path.join(app_path, 'Contents', 'MacOS', 'PyQt5',
                                  'Qt', 'lib', 'QtWebEngineCore.framework')

    core_lib = os.path.join(framework_path, 'Versions', '5', 'QtWebEngineCore')
    os.remove(core_lib)
    core_target = os.path.join(*[os.pardir] * 7, 'MacOS', 'QtWebEngineCore')
    os.symlink(core_target, core_lib)

    framework_resource_path = os.path.join(framework_path, 'Resources')
    for name in os.listdir(framework_resource_path):
        file_path = os.path.join(framework_resource_path, name)
        target = os.path.join(*[os.pardir] * 5, name)
        if os.path.isdir(file_path):
            shutil.rmtree(file_path)
        else:
            os.remove(file_path)
        os.symlink(target, file_path) 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:32,代码来源:build_release.py

示例14: get_sorted_wifis

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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)
    ) 
开发者ID:Mebus,项目名称:restatic,代码行数:36,代码来源:utils.py

示例15: do_plist

# 需要导入模块: import plistlib [as 别名]
# 或者: from plistlib import load [as 别名]
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 
开发者ID:fgimian,项目名称:macbuild-ansible,代码行数:31,代码来源:plist.py


注:本文中的plistlib.load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。