• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python toml.loads函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中toml.loads函数的典型用法代码示例。如果您正苦于以下问题:Python loads函数的具体用法?Python loads怎么用?Python loads使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: parsed_pipfile

    def parsed_pipfile(self):
        # Open the pipfile, read it into memory.
        with open(self.pipfile_location) as f:
            contents = f.read()

        # If any outline tables are present...
        if ('[packages.' in contents) or ('[dev-packages.' in contents):

            data = toml.loads(contents)

            # Convert all outline tables to inline tables.
            for section in ('packages', 'dev-packages'):
                for package in data.get(section, {}):

                    # Convert things to inline tables — fancy :)
                    if hasattr(data[section][package], 'keys'):
                        _data = data[section][package]
                        data[section][package] = toml._get_empty_inline_table(dict)
                        data[section][package].update(_data)

            # We lose comments here, but it's for the best.)
            try:
                return contoml.loads(toml.dumps(data, preserve=True))
            except RuntimeError:
                return toml.loads(toml.dumps(data, preserve=True))

        else:
            # Fallback to toml parser, for large files.
            try:
                return contoml.loads(contents)
            except Exception:
                return toml.loads(contents)
开发者ID:cogzidel,项目名称:healthchecks,代码行数:32,代码来源:project.py


示例2: read

def read():
    default_config = Config({
        'credentials': {
            'stack-exchange': {
                'email': '',
                'password': '',
            },
        },
        'resources': {
            'db': 'sqlite:///:memory:',
        },
        'state': {
            'params': {
                '--server': 'se',
                '--room': '70095',
                '--user': '-2',
            },
            'room-tailed-times': {
                'se': {},
                'so': {},
                'mse': {},
            },
        },
    })
    global_config = Config(toml.loads(open('~/.stack.chat.toml')))
    local_config = Config(
        default_config, global_config, toml.loads(open('./.stack.chat.toml')))
    
    return local_config
开发者ID:jeremybanks,项目名称:ChatExchange,代码行数:29,代码来源:__init__.py


示例3: _parse_pipfile

    def _parse_pipfile(self, contents):
        # If any outline tables are present...
        if ("[packages." in contents) or ("[dev-packages." in contents):
            data = toml.loads(contents)
            # Convert all outline tables to inline tables.
            for section in ("packages", "dev-packages"):
                for package in data.get(section, {}):
                    # Convert things to inline tables — fancy :)
                    if hasattr(data[section][package], "keys"):
                        _data = data[section][package]
                        data[section][package] = toml._get_empty_inline_table(dict)
                        data[section][package].update(_data)
            # We lose comments here, but it's for the best.)
            try:
                return contoml.loads(toml.dumps(data, preserve=True))

            except RuntimeError:
                return toml.loads(toml.dumps(data, preserve=True))

        else:
            # Fallback to toml parser, for large files.
            try:
                return contoml.loads(contents)

            except Exception:
                return toml.loads(contents)
开发者ID:TimexStudio,项目名称:pipenv,代码行数:26,代码来源:project.py


示例4: test_normal

    def test_normal(self, capsys, table_name, header, value, expected):
        writer = table_writer_class()
        writer.table_name = table_name
        writer.headers = header
        writer.value_matrix = value
        writer.write_table()

        out, err = capsys.readouterr()
        print_test_result(expected=expected, actual=out, error=err)

        assert toml.loads(out) == toml.loads(expected)
开发者ID:thombashi,项目名称:pytablewriter,代码行数:11,代码来源:test_toml_writer.py


示例5: _loadfile

def _loadfile(fname, logger):
    conf_dict = {}

    if os.path.exists(fname):
        # file exists
        if HAVE_TOML:
            conf_dict = toml.loads(open(fname).read())
        else:
            raise ImportError("No module named toml")

        include_files = []
        if "include" in conf_dict.keys():
            if "file" in conf_dict["include"].keys():
                f = conf_dict["include"]["file"]
                include_files.append(os.path.expanduser(f))

            if "directory" in conf_dict["include"].keys():
                d = conf_dict["include"]["directory"]
                include_files = include_files + sorted([os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser(d)) for f in fn])

        for f in include_files:
            try:
                _merge(conf_dict, _loadfile(f, logger))
            except Exception as e:
                logger.error("Config file parse error: " + str(f) + " " + str(e).split("\n")[0])

        if HAVE_JSONSCHEMA:
            validate(conf_dict, json.loads(_confspec))
        else:
            raise ImportError("No module named jsonschema")

    return conf_dict
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:32,代码来源:conf.py


示例6: repack

def repack(host, targets, channel='stable', suffix=''):
  print("Repacking rust for %s..." % host)
  url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'
  req = requests.get(url)
  req.raise_for_status()
  manifest = toml.loads(req.content)
  if manifest['manifest-version'] != '2':
    print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])
    return
  print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))
  print('Fetching packages...')
  rustc = fetch_package(manifest, 'rustc', host)
  cargo = fetch_package(manifest, 'cargo', host)
  stds = fetch_std(manifest, targets)
  print('Installing packages...')
  tar_basename = 'rustc-' + host
  if suffix:
      tar_basename += '-' + suffix
  tar_basename += '-repack'
  install_dir = 'rustc'
  subprocess.check_call(['rm', '-rf', install_dir])
  install(os.path.basename(rustc['url']), install_dir)
  install(os.path.basename(cargo['url']), install_dir)
  for std in stds:
    install(os.path.basename(std['url']), install_dir)
    pass
  print('Tarring %s...' % tar_basename)
  tar_options, tar_ext = tar_for_host(host)
  subprocess.check_call(['tar', tar_options, tar_basename + tar_ext, install_dir])
  subprocess.check_call(['rm', '-rf', install_dir])
开发者ID:MichaelKohler,项目名称:gecko-dev,代码行数:30,代码来源:repack_rust.py


示例7: load_config

def load_config():
    filename = sys.argv[1] if len(sys.argv) > 1 else 'benchmark.toml'
    with open(filename) as configfile:
        config = toml.loads(configfile.read())
    items = config['item']
    default = items['default']
    if 'options' in config:
        options = config['options']
    else:
        options = dict(ref_result="C",
                       time_field="elapsed",
                       show_diff_below=0.9,
                       verbose=True)
    ret_items = {}
    for name, item in zip(items, items.values()):
        if name == 'default':
            continue
        if name.startswith('"') and name.endswith('"'):
            import ast
            name = ast.literal_eval(name)
        profile = dict(default)
        profile.update(item)
        profile['name'] = name
        for k, v in zip(profile, profile.values()):
            if type(v) is str:
                profile[k] = Template(v).safe_substitute(**profile)
        ret_items[name] = profile
    return ret_items, options
开发者ID:FrankHB,项目名称:swapview,代码行数:28,代码来源:bench.py


示例8: load_config

def load_config(filename):
    if not path.exists(filename):
        print 'no such file: {0}'.format(filename)
        exit()
    with open(filename) as fid:
        config = toml.loads(fid.read())
    return config
开发者ID:mwv,项目名称:ldtw,代码行数:7,代码来源:distances.py


示例9: main

def main() -> None:
    data = toml.load(sys.stdin)

    assert list(data.keys()) == ["source"]

    # this value is non deterministic
    data["source"]["vendored-sources"]["directory"] = "@[email protected]"

    lines = []
    inner = data["source"]
    for source, attrs in sorted(inner.items()):
        lines.append("[source.{}]".format(quote(source)))
        if source == "vendored-sources":
            lines.append('"directory" = "@[email protected]"\n')
        else:
            for key, value in sorted(attrs.items()):
                attr = "{} = {}".format(quote(key), quote(value))
                lines.append(attr)
        lines.append("")

    result = "\n".join(lines)
    real = toml.loads(result)
    assert real == data, "output = {} while input = {}".format(real, data)

    print(result)
开发者ID:AndersonTorres,项目名称:nixpkgs,代码行数:25,代码来源:cargo-vendor-normalise.py


示例10: parse

    def parse(self):
        # Open the Pipfile.
        with open(self.filename) as f:
            content = f.read()

        # Load the default configuration.
        default_config = {
            u'source': [{u'url': u'https://pypi.python.org/simple', u'verify_ssl': True, 'name': "pypi"}],
            u'packages': {},
            u'requires': {},
            u'dev-packages': {}
        }

        config = {}
        config.update(default_config)

        # Load the Pipfile's configuration.
        config.update(toml.loads(content))

        # Structure the data for output.
        data = {
            '_meta': {
                'sources': config['source'],
                'requires': config['requires']
            },
        }

        # TODO: Validate given data here.
        self.groups['default'] = config['packages']
        self.groups['develop'] = config['dev-packages']

        # Update the data structure with group information.
        data.update(self.groups)
        return data
开发者ID:moshez,项目名称:pipfile,代码行数:34,代码来源:api.py


示例11: get_pages_from_dirs

def get_pages_from_dirs(dirs):
    pages = []
    for dir in dirs:
        page = {}

        path_to_metadata_file = path.join(dir, conf["metadata_file"])
        with open(path_to_metadata_file) as metadata_file:
            page = toml.loads(metadata_file.read())

        try:
            for key in conf["required_keys_in_page"]:
                page[key]
        except KeyError:
            message = "`{}` key is missing from metadata file!".format(key)
            logger.error(message)
            exit()

        content_path = path.join(dir, page["content_path"])
        content_path = glob.glob(content_path)
        if len(content_path) != 1:
            logger.error("Content path matched less or more than needed!")
            exit()
        content_path = content_path[0]

        with open(content_path) as content_file:
            page["content"] = content_file.read()

        pages.append(page)

    return pages
开发者ID:daGrevis,项目名称:squirrel,代码行数:30,代码来源:__init__.py


示例12: load_toml_path_config

def load_toml_path_config(filename):
    """Returns a PathConfig created by loading a TOML file from the
    filesystem.
    """
    if not os.path.exists(filename):
        LOGGER.info(
            "Skipping path loading from non-existent config file: %s",
            filename)
        return PathConfig()

    LOGGER.info("Loading path information from config: %s", filename)

    try:
        with open(filename) as fd:
            raw_config = fd.read()
    except IOError as e:
        raise LocalConfigurationError(
            "Unable to load path configuration file: {}".format(str(e)))

    toml_config = toml.loads(raw_config)

    invalid_keys = set(toml_config.keys()).difference(
        ['data_dir', 'key_dir', 'log_dir'])
    if invalid_keys:
        raise LocalConfigurationError("Invalid keys in path config: {}".format(
            ", ".join(sorted(list(invalid_keys)))))

    config = PathConfig(
        config_dir=None,
        data_dir=toml_config.get('data_dir', None),
        key_dir=toml_config.get('key_dir', None),
        log_dir=toml_config.get('log_dir', None)
    )

    return config
开发者ID:feihujiang,项目名称:sawtooth-core,代码行数:35,代码来源:path.py


示例13: __init__

    def __init__(self):
        
        conf_fn = "conf.toml"

        with open(conf_fn) as conf_fh:   
            toml_str = conf_fh.read()
            self.conf = toml.loads(toml_str)
开发者ID:mabotech,项目名称:mabo.task,代码行数:7,代码来源:config.py


示例14: get_server

def get_server():
    config_file = os.path.join(config.get_config_dir(), 'ias_proxy.toml')
    LOGGER.info('Loading IAS Proxy config from: %s', config_file)

    # Lack of a config file is a fatal error, so let the exception percolate
    # up to caller
    with open(config_file) as fd:
        proxy_config = toml.loads(fd.read())

    # Verify the integrity (as best we can) of the TOML configuration file
    valid_keys = set(['proxy_name', 'proxy_port', 'ias_url', 'spid_cert_file'])
    found_keys = set(proxy_config.keys())

    invalid_keys = found_keys.difference(valid_keys)
    if invalid_keys:
        raise \
            ValueError(
                'IAS Proxy config file contains the following invalid '
                'keys: {}'.format(
                    ', '.join(sorted(list(invalid_keys)))))

    missing_keys = valid_keys.difference(found_keys)
    if missing_keys:
        raise \
            ValueError(
                'IAS Proxy config file missing the following keys: '
                '{}'.format(
                    ', '.join(sorted(list(missing_keys)))))

    return IasProxyServer(proxy_config)
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:30,代码来源:ias_proxy.py


示例15: setUp

    def setUp(self):
        """
        Initialize the system configuration and the user configuration.

        Note the forward slash replacements for the user configuration. This is due to the forward slash being a
        restricted character in TOML(package used to parse configuration files in LQMT).
        """
        # relative pathing variables. Replace function calls for Windows compatibility.
        self.directory = os.path.dirname(__file__)
        self.alerts = self.directory + "/test_data/"
        self.alerts = self.alerts.replace("\\", "/")
        self.logging = self.directory + "/test_data/test-logs/lqmt"
        self.logging = self.logging.replace("\\", "/")
        self.whitelist = self.directory + "/test_data/whitelist/whitelist.txt"
        self.whitelist = self.whitelist.replace("\\", "/")
        self.whitelist_db = self.directory + "/test_data/whitelist/whitelist.db"
        self.whitelist_db = self.whitelist_db.replace("\\", "/")

        # configurations initialized
        sysconf = SystemConfig()
        self.sys_config = sysconf.getConfig()
        config = USERCONFIG.format(self.alerts, self.logging, self.whitelist, self.whitelist_db)
        self.toml_config = toml.loads(config)
        self.toml_config = self.toml_config["Tools"]["FlexText"][0]  # dirty way of parsing userconfig for ToolConfig
        self.user_config = LQMToolConfig(config)
        self.toolConfig = ToolConfig(self.toml_config, csvToolInfo={""}, unhandledCSV={""})
开发者ID:anl-cyberscience,项目名称:LQMToolset,代码行数:26,代码来源:configuration_test.py


示例16: read_toml

def read_toml(content):
    check_section_header(content)
    for k, v in toml.loads(content, collections.OrderedDict).items():
        if len(v.values()) and isinstance(list(v.values())[0], dict):
            raise RuntimeError('malformed section header -- forgot quotes?', k)
        pname, version = split_name(k)
        yield WhitelistRule(pname=pname, version=version, **v)
开发者ID:flyingcircusio,项目名称:vulnix,代码行数:7,代码来源:whitelist.py


示例17: __init__

    def __init__(self, context):
        self.context = context

        if not hasattr(self.context, "bootstrapped"):
            self.context.bootstrapped = False

        if not hasattr(self.context, "sharedir"):
            self.context.sharedir = path.join(path.expanduser("~/"), ".servo")

        config_path = path.join(context.topdir, ".servobuild")
        if path.exists(config_path):
            self.config = toml.loads(open(config_path).read())
        else:
            self.config = {}

        # Handle missing/default items
        self.config.setdefault("tools", {})
        self.config["tools"].setdefault("system-rust", False)
        self.config["tools"].setdefault("system-cargo", False)
        self.config["tools"].setdefault("rust-root", "")
        self.config["tools"].setdefault("cargo-root", "")
        if not self.config["tools"]["system-rust"]:
            self.config["tools"]["rust-root"] = path.join(
                context.sharedir, "rust", *self.rust_snapshot_path().split("/"))
        if not self.config["tools"]["system-cargo"]:
            self.config["tools"]["cargo-root"] = path.join(
                context.sharedir, "cargo", self.cargo_build_id())

        self.config.setdefault("build", {})
        self.config["build"].setdefault("android", False)

        self.config.setdefault("android", {})
        self.config["android"].setdefault("sdk", "")
        self.config["android"].setdefault("ndk", "")
        self.config["android"].setdefault("toolchain", "")
开发者ID:neojski,项目名称:servo,代码行数:35,代码来源:command_base.py


示例18: get_config

def get_config():
    # Read config parameters from a TOML file.
    config = None
    config_file_path = sys.argv[1]
    with open(config_file_path) as config_file:
        config = toml.loads(config_file.read())
    return config
开发者ID:julianespinel,项目名称:stockreader,代码行数:7,代码来源:stockreader.py


示例19: __parse_config

    def __parse_config(self, configfile):
        """
        Extracts the defined configuration parameters for the parser.
        Important pre-condition is the user must configure elements and rules against a predefined enumeration.

        :param configfile: configuration file
        :return None:
        """
        if os.path.exists(configfile):
            cfg = open(configfile)
            topconfig = toml.loads(cfg.read())
            cfg.close()

            if 'Filters' in topconfig:
                if 'sources' in topconfig['Filters'][0]:
                    self._sources = topconfig['Filters'][0]['sources']

                if 'rules' in topconfig['Filters'][0]:
                    temp = topconfig['Filters'][0]['rules']
                    for x in temp:
                        if x.lower() in self._accepted_rules:
                            self._rules.append(x.lower())
                        else:
                            self._logger.warning("Incompatible rule for parser " + x)

                if 'start_offset' in topconfig['Filters'][0]:
                    self._line_offset = topconfig['Filters'][0]['start_offset']
开发者ID:anl-cyberscience,项目名称:LQMToolset,代码行数:27,代码来源:parser.py


示例20: __init__

    def __init__(self, context):
        self.context = context

        def get_env_bool(var, default):
            # Contents of env vars are strings by default. This returns the
            # boolean value of the specified environment variable, or the
            # speciried default if the var doesn't contain True or False
            return {'True': True, 'False': False}.get(os.environ.get(var), default)

        def resolverelative(category, key):
            # Allow ~
            self.config[category][key] = path.expanduser(self.config[category][key])
            # Resolve relative paths
            self.config[category][key] = path.join(context.topdir,
                                                   self.config[category][key])

        if not hasattr(self.context, "bootstrapped"):
            self.context.bootstrapped = False

        config_path = path.join(context.topdir, ".servobuild")
        if path.exists(config_path):
            with open(config_path) as f:
                self.config = toml.loads(f.read())
        else:
            self.config = {}

        # Handle missing/default items
        self.config.setdefault("tools", {})
        default_cache_dir = os.environ.get("SERVO_CACHE_DIR",
                                           path.join(context.topdir, ".servo"))
        self.config["tools"].setdefault("cache-dir", default_cache_dir)
        resolverelative("tools", "cache-dir")

        default_cargo_home = os.environ.get("CARGO_HOME",
                                            path.join(context.topdir, ".cargo"))
        self.config["tools"].setdefault("cargo-home-dir", default_cargo_home)
        resolverelative("tools", "cargo-home-dir")

        context.sharedir = self.config["tools"]["cache-dir"]

        self.config["tools"].setdefault("use-rustup", True)
        self.config["tools"].setdefault("rustc-with-gold", get_env_bool("SERVO_RUSTC_WITH_GOLD", True))

        self.config.setdefault("build", {})
        self.config["build"].setdefault("android", False)
        self.config["build"].setdefault("mode", "")
        self.config["build"].setdefault("debug-mozjs", False)
        self.config["build"].setdefault("ccache", "")
        self.config["build"].setdefault("rustflags", "")
        self.config["build"].setdefault("incremental", None)
        self.config["build"].setdefault("thinlto", False)
        self.config["build"].setdefault("webgl-backtrace", False)
        self.config["build"].setdefault("dom-backtrace", False)

        self.config.setdefault("android", {})
        self.config["android"].setdefault("sdk", "")
        self.config["android"].setdefault("ndk", "")
        self.config["android"].setdefault("toolchain", "")
        # Set default android target
        self.handle_android_target("armv7-linux-androideabi")
开发者ID:ToBeFree,项目名称:servo,代码行数:60,代码来源:command_base.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tomopy.angles函数代码示例发布时间:2022-05-27
下一篇:
Python toml.load函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap