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


Python toml.loads函数代码示例

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


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


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