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


Python Property.parse方法代码示例

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


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

示例1: init_trans

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
    def init_trans(self):
        """Try and load a copy of basemodui from Portal 2 to translate.

        Valve's items use special translation strings which would look ugly
        if we didn't convert them.
        """
        # Already loaded
        if TRANS_DATA:
            return

        # We need to first figure out what language is used (if not English),
        # then load in the file. This is saved in the 'appmanifest',

        try:
            appman_file = open(self.abs_path("../../appmanifest_620.acf"))
        except FileNotFoundError:
            # Portal 2 isn't here...
            return
        with appman_file:
            appman = Property.parse(appman_file, "appmanifest_620.acf")
        try:
            lang = appman.find_key("AppState").find_key("UserConfig")["language"]
        except NoKeyError:
            return

        basemod_loc = self.abs_path("../Portal 2/portal2_dlc2/resource/basemodui_" + lang + ".txt")

        # Basemod files are encoded in UTF-16.
        try:
            basemod_file = open(basemod_loc, encoding="utf16")
        except FileNotFoundError:
            return
        with basemod_file:
            if lang == "english":

                def filterer(file):
                    """The English language has some unused language text.

                    This needs to be skipped since it has invalid quotes."""
                    for line in file:
                        if line.count('"') <= 4:
                            yield line

                basemod_file = filterer(basemod_file)

            trans_prop = Property.parse(basemod_file, "basemodui.txt")

        for item in trans_prop.find_key("lang", []).find_key("tokens", []):
            TRANS_DATA[item.real_name] = item.value
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:51,代码来源:gameMan.py

示例2: clean_text

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
def clean_text(file_path):
    # Try and parse as a property file. If it succeeds,
    # write that out - it removes excess whitespace between lines
    with open(file_path, 'r') as f:
        try: 
            props = Property.parse(f)
        except KeyValError:
            pass
        else:
            for line in props.export():
                yield line.lstrip()
            return
    
    with open(file_path, 'r') as f:
        for line in f:
            if line.isspace():
                continue
            if line.lstrip().startswith('//'):
                continue
            # Remove // comments, but only if the comment doesn't have
            # a quote char after it - it could be part of the string,
            # so leave it just to be safe.
            if '//' in line and '"' not in line:
                yield line.split('//')[0] + '\n'
            else:
                yield line.lstrip()
开发者ID:xDadiKx,项目名称:BEE2-items,代码行数:28,代码来源:compile_packages.py

示例3: read_settings

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
def read_settings() -> None:
    """Read and apply the settings from disk."""
    try:
        file = open(utils.conf_location('config/config.vdf'), encoding='utf8')
    except FileNotFoundError:
        return
    with file:
        props = Property.parse(file)
    apply_settings(props)
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:11,代码来源:BEE2_config.py

示例4: load_config

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
def load_config():
    global CONF
    LOGGER.info('Loading Settings...')
    try:
        with open("bee2/vrad_config.cfg", encoding='utf8') as config:
            CONF = Property.parse(config, 'bee2/vrad_config.cfg').find_key(
                'Config', []
            )
    except FileNotFoundError:
        pass
    LOGGER.info('Config Loaded!')
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:13,代码来源:vrad.py

示例5: from_file

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
    def from_file(cls, path, zip_file):
        """Initialise from a file.

        path is the file path for the map inside the zip, without extension.
        zip_file is either a ZipFile or FakeZip object.
        """
        # Some P2Cs may have non-ASCII characters in descriptions, so we
        # need to read it as bytes and convert to utf-8 ourselves - zips
        # don't convert encodings automatically for us.
        try:
            with zip_open_bin(zip_file, path + '.p2c') as file:
                props = Property.parse(
                    # Decode the P2C as UTF-8, and skip unknown characters.
                    # We're only using it for display purposes, so that should
                    # be sufficent.
                    TextIOWrapper(
                        file,
                        encoding='utf-8',
                        errors='replace',
                    ),
                    path,
                )
        except KeyValError:
            # Silently fail if we can't parse the file. That way it's still
            # possible to backup.
            LOGGER.warning('Failed parsing puzzle file!', path, exc_info=True)
            props = Property('portal2_puzzle', [])
            title = None
            desc = _('Failed to parse this puzzle file. It can still be backed up.')
        else:
            props = props.find_key('portal2_puzzle', [])
            title = props['title', None]
            desc = props['description', _('No description found.')]



        if title is None:
            title = '<' + path.rsplit('/', 1)[-1] + '.p2c>'

        return cls(
            filename=os.path.basename(path),
            zip_file=zip_file,
            title=title,
            desc=desc,
            is_coop=srctools.conv_bool(props['coop', '0']),
            create_time=Date(props['timestamp_created', '']),
            mod_time=Date(props['timestamp_modified', '']),
        )
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:50,代码来源:backup.py

示例6: gen_vpks

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
def gen_vpks():
    with open('vpk/vpk_dest.cfg') as f:
        config = Property.parse(f, 'vpk/vpk_dest.cfg').find_key("VPKDest", [])
        
    if not os.path.isfile(VPK_BIN_LOC):
        print('VPK.exe not present, skipping VPK generation.')
        return
        
    for prop in config:
        src = os.path.join('vpk', prop.real_name)
        dest = os.path.abspath('packages/{}/{}.vpk'.format(prop.value, src))
        
        subprocess.call([
            VPK_BIN_LOC,
            src,
        ])
        
        if os.path.isfile(dest):
            os.remove(dest)
        os.rename(src + '.vpk', dest)
        print('Processed "{}"'.format(dest))
开发者ID:xDadiKx,项目名称:BEE2-items,代码行数:23,代码来源:compile_packages.py

示例7: parse_legacy

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
def parse_legacy(posfile, propfile, path):
    """Parse the original BEE2.2 palette format."""
    props = Property.parse(propfile, path + ':properties.txt')
    name = props['name', 'Unnamed']
    pos = []
    for dirty_line in posfile:
        line = srctools.clean_line(dirty_line)
        if line:
            # Lines follow the form
            # "ITEM_BUTTON_FLOOR", 2
            # for subtype 3 of the button
            if line.startswith('"'):
                val = line.split('",')
                if len(val) == 2:
                    pos.append((
                        val[0][1:], # Item ID
                        int(val[1].strip()), # Item subtype
                        ))
                else:
                    LOGGER.warning('Malformed row "{}"!', line)
                    return None
    return Palette(name, pos)
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:24,代码来源:paletteLoader.py

示例8: parse

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
    def parse(cls, path: str):
        with open(path, encoding='utf8') as f:
            props = Property.parse(f, path)
        name = props['Name', '??']
        items = []
        for item in props.find_children('Items'):
            items.append((item.real_name, int(item.value)))

        trans_name = props['TransName', '']

        try:
            settings = props.find_key('Settings')
        except NoKeyError:
            settings = None

        return Palette(
            name,
            items,
            trans_name=trans_name,
            prevent_overwrite=props.bool('readonly'),
            filename=os.path.basename(path),
            settings=settings,
        )
开发者ID:BenVlodgi,项目名称:BEE2.4,代码行数:25,代码来源:paletteLoader.py

示例9: __init__

# 需要导入模块: from srctools import Property [as 别名]
# 或者: from srctools.Property import parse [as 别名]
    def __init__(self, path: Union[str, Path]):
        """Parse a game from a folder."""
        if isinstance(path, Path):
            self.path = path
        else:
            self.path = Path(path)
        with open(self.path / GINFO) as f:
            gameinfo = Property.parse(f).find_key('GameInfo')
        fsystems = gameinfo.find_key('Filesystem', [])

        self.game_name = gameinfo['Game']
        self.app_id = fsystems['SteamAppId']
        self.tools_id = fsystems['ToolsAppId', None]
        self.additional_content = fsystems['AdditionalContentId', None]
        self.fgd_loc = gameinfo['GameData', 'None']
        self.search_paths = []  # type: List[Path]

        for path in fsystems.find_children('SearchPaths'):
            self.search_paths.append(self.parse_search_path(self.path.parent, path))

        # Add DLC folders based on the first/bin folder.
        try:
            first_search = self.search_paths[0]
        except IndexError:
            pass
        else:
            folder = first_search.parent
            stem = first_search.name + '_dlc'
            for ind in itertools.count(1):
                path = folder / (stem + str(ind))
                if path.exists():
                    self.search_paths.insert(0, path)
                else:
                    break

            # Force including 'platform', for Hammer assets.
            self.search_paths.append(self.path.parent / 'platform')
开发者ID:TeamSpen210,项目名称:srctools,代码行数:39,代码来源:game.py


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