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


Python toml.loads方法代码示例

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


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

示例1: _get_config

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def _get_config():
    """Determines if there is a log config in the config directory
       and returns it. If it does not exist, return None.

    Returns:
        log_config (dict): The dictionary to pass to logging.config.dictConfig
    """
    conf_file = os.path.join(_get_config_dir(), 'log_config.toml')
    if os.path.exists(conf_file):
        with open(conf_file) as fd:
            raw_config = fd.read()
        log_config = toml.loads(raw_config)
        return log_config

    conf_file = os.path.join(_get_config_dir(), 'log_config.yaml')
    if os.path.exists(conf_file):
        with open(conf_file) as fd:
            raw_config = fd.read()
        log_config = yaml.safe_load(raw_config)
        return log_config

    return None 
开发者ID:hyperledger,项目名称:sawtooth-core,代码行数:24,代码来源:logs.py

示例2: _load_toml_cli_config

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def _load_toml_cli_config(filename=None):
    if filename is None:
        filename = os.path.join(
            _get_config_dir(),
            'cli.toml')

    if not os.path.exists(filename):
        LOGGER.info(
            "Skipping CLI config loading from non-existent config file: %s",
            filename)

        return {}

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

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

    return toml.loads(raw_config) 
开发者ID:hyperledger,项目名称:sawtooth-core,代码行数:25,代码来源:cli_config.py

示例3: update

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def update(cls, content, dependency, version, spec="==", hashes=()):
        data = toml.loads(content)
        if data:
            for package_type in ['packages', 'dev-packages']:
                if package_type in data:
                    if dependency.full_name in data[package_type]:
                        data[package_type][dependency.full_name] = "{spec}{version}".format(
                            spec=spec, version=version
                        )
        try:
            from pipenv.project import Project
        except ImportError:
            raise ImportError("Updating a Pipfile requires the pipenv extra to be installed. Install it with "
                              "pip install dparse[pipenv]")
        pipfile = tempfile.NamedTemporaryFile(delete=False)
        p = Project(chdir=False)
        p.write_toml(data=data, path=pipfile.name)
        data = open(pipfile.name).read()
        os.remove(pipfile.name)
        return data 
开发者ID:pypa,项目名称:pipenv,代码行数:22,代码来源:updater.py

示例4: read_config

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def read_config(args):
    """ Read configuration options from ~/.shakedown (if exists)

        :param args: a dict of arguments
        :type args: dict

        :return: a dict of arguments
        :rtype: dict
    """

    configfile = os.path.expanduser('~/.shakedown')

    if os.path.isfile(configfile):
        with open(configfile, 'r') as f:
            config = toml.loads(f.read())

        for key in config:
            param = key.replace('-', '_')

            if not param in args or args[param] in [False, None]:
                args[param] = config[key]

    return args 
开发者ID:dcos,项目名称:shakedown,代码行数:25,代码来源:helpers.py

示例5: mock_config

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def mock_config():
    """Create a mock config for documentation and testing purposes."""
    from . import config

    filename = Path(pkgrf("mriqc", "data/config-example.toml"))
    settings = loads(filename.read_text())
    for sectionname, configs in settings.items():
        if sectionname != "environment":
            section = getattr(config, sectionname)
            section.load(configs, init=False)
    config.nipype.init()
    config.loggers.init()

    config.execution.work_dir = Path(mkdtemp())
    config.execution.bids_dir = Path(pkgrf("mriqc", "data/tests/ds000005")).absolute()
    config.execution.init()

    yield 
开发者ID:poldracklab,项目名称:mriqc,代码行数:20,代码来源:testing.py

示例6: convert_graph

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def convert_graph(model_file, output_nodes=None, config='utensor_cli.toml', target='utensor', model_name=None):
  from utensor_cgen.frontend import FrontendSelector

  if os.path.exists(config):
    logger.info('config file {} found, reading configurations'.format(config))
    with open(config) as fid:
      config = loads(fid.read())
  else:
    config = {}
  ugraph = FrontendSelector.parse(
    model_file, output_nodes,
    config=config,
    model_name=model_name
  )
  backend = BackendManager.get_backend(target)(config)
  backend.apply(ugraph)
  return ugraph 
开发者ID:uTensor,项目名称:utensor_cgen,代码行数:19,代码来源:convert.py

示例7: __init__

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def __init__(self):
        # Load entity config
        config_path = os.path.abspath(settings.BASE_DIR + '/config.toml')
        try:
            with open(config_path, 'r') as config_file:
                config_toml = config_file.read()
        except FileNotFoundError as e:
            logger.error('Could not find config.toml. Exiting.')
            raise

        self.config = toml.loads(config_toml)

        genesis_txn_path = "/app/.genesis"

        checkGenesisFile(genesis_txn_path)
        self.config["genesis_txn_path"] = genesis_txn_path
        # bhs: configuring/grabbing the wallet seed is now done through agent.py
        # at least in theory. so i'm commenting this one out to make sure
        # we are using the same env vars as much as possible :(
        #
        # Wallet seeds should be configurable through env or the config file
#        self.config["wallet_seed"] = os.getenv('WALLET_SEED',
#            self.config["wallet_seed"]) 
开发者ID:IBM-Blockchain-Identity,项目名称:indy-ssivc-tutorial,代码行数:25,代码来源:config.py

示例8: is_registered

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def is_registered(self) -> bool:
        """Check whether or not the repository belongs to a registered package."""
        try:
            root = self._registry_path
        except InvalidProject as e:
            logger.debug(e.message)
            return False
        if not root:
            return False
        contents = self._only(self._registry.get_contents(f"{root}/Package.toml"))
        package = toml.loads(contents.decoded_content.decode())
        gh = cast(str, urlparse(self._gh_url).hostname).replace(".", r"\.")
        if "@" in package["repo"]:
            pattern = rf"{gh}:(.*?)(?:\.git)?$"
        else:
            pattern = rf"{gh}/(.*?)(?:\.git)?$"
        m = re.search(pattern, package["repo"])
        if not m:
            return False
        # I'm not really sure why mypy doesn't like this line without the cast.
        return cast(bool, m[1].casefold() == self._repo.full_name.casefold()) 
开发者ID:JuliaRegistries,项目名称:TagBot,代码行数:23,代码来源:repo.py

示例9: loads

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def loads(cls, string: str) -> 'Shortcut':
        from shortcuts import Shortcut  # noqa

        if isinstance(string, (bytearray, bytes)):
            string = string.decode('utf-8')

        shortcut_dict = toml.loads(string)
        shortcut = Shortcut(name=shortcut_dict.get('name', 'python-shortcuts'))

        if not isinstance(shortcut_dict.get('action'), list):
            raise ValueError('toml file must contain "action" array with actions')

        for params in shortcut_dict['action']:
            action_params = copy.deepcopy(params)
            del action_params['type']

            action_class = actions_registry.get_by_keyword(params['type'])
            action = action_class(data=action_params)
            shortcut.actions.append(action)

        return shortcut 
开发者ID:alexander-akhmetov,项目名称:python-shortcuts,代码行数:23,代码来源:loader.py

示例10: collect_env

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def collect_env(args):
    PROJ_DIR = look_for_proj_dir(os.path.abspath(__file__), 'pubspec.yaml')
    RUST_PROJ_DIR = os.path.join(PROJ_DIR, 'rust')
    RUST_ASSETS_DIR = os.path.join(RUST_PROJ_DIR, 'assets')
    TOML_FILE = os.path.join(RUST_PROJ_DIR, 'Cargo.toml')
    META = toml.loads(open(TOML_FILE).read())
    NAME = META['package']['name']
    VERSION = META['package']['version']
    DESCRIPTION = META['package']['description']

    DEBUG = not args.release
    RELEASE = args.release

    TARGET_DIR = os.path.join(RUST_PROJ_DIR, 'target')
    WORKSPACE = get_workspace_dir(RUST_PROJ_DIR)
    WORKSPACE_TARGET_DIR = os.path.join(WORKSPACE, 'target') if WORKSPACE else None
    OUTPUT_DIR = os.path.join(TARGET_DIR, 'debug' if DEBUG else 'release')
    FLUTTER_CONFIG = META['package']['metadata']['flutter']
    IDENTIFIER =  FLUTTER_CONFIG['identifier'] if 'identifier' in FLUTTER_CONFIG else 'one.juju.flutter-app'
    FLUTTER_LIB_VER = get_flutter_version()
    FLUTTER_ASSETS = os.path.join(os.path.dirname(RUST_PROJ_DIR), 'build', 'flutter_assets')
    return locals() 
开发者ID:gliheng,项目名称:flutter-app-template,代码行数:24,代码来源:build.py

示例11: apiPlaceOrderNew

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def apiPlaceOrderNew(session, shopurl, hostid, toraddressWithPort):

    print("# apiPlaceOrderNew")

    try:
        postData={
            'product': "tor_bridge",
            'host_id': hostid,
            'tos_accepted': True,
            'comment': 'test',
            'target': toraddressWithPort,
            'public_key': ''
        }  
        response = session.post("{0}/api/v1/public/order/".format(shopurl), data=postData)
    except Exception as e:
        eprint(e)
        print("error='FAILED HTTP REQUEST'")
        return
    if response.status_code != 201:
        eprint(response.content)
        print("error='FAILED HTTP CODE ({0}) != 201'".format(response.status_code))
        return

    # parse & validate data
    try:
        jData = json.loads(response.content)
        if len(jData['id']) == 0:
            print("error='MISSING ID'")
            return
    except Exception as e:
        eprint(e)
        print("error='FAILED JSON PARSING'")
        return

    return jData['id'] 
开发者ID:rootzoll,项目名称:raspiblitz,代码行数:37,代码来源:blitz.ip2tor.py

示例12: apiPlaceOrderExtension

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def apiPlaceOrderExtension(session, shopurl, bridgeid):

    print("# apiPlaceOrderExtension")

    try:
        url="{0}/api/v1/public/tor_bridges/{1}/extend/".format(shopurl, bridgeid)
        response = session.post(url)
    except Exception as e:
        eprint(url)
        eprint(e)
        print("error='FAILED HTTP REQUEST'")
        return
    if response.status_code != 200 and response.status_code != 201:
        eprint(response.content)
        print("error='FAILED HTTP CODE ({0}) != 201'".format(response.status_code))
        return

    # parse & validate data
    try:
        jData = json.loads(response.content)
        if len(jData['po_id']) == 0:
            print("error='MISSING ID'")
            return
    except Exception as e:
        eprint(e)
        print("error='FAILED JSON PARSING'")
        return

    return jData['po_id'] 
开发者ID:rootzoll,项目名称:raspiblitz,代码行数:31,代码来源:blitz.ip2tor.py

示例13: apiGetOrder

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def apiGetOrder(session, shopurl, orderid):

    print("# apiGetOrder")

    # make HTTP request
    try:
        response = session.get("{0}/api/v1/public/pos/{1}/".format(shopurl,orderid))
    except Exception as e:
        eprint(e)
        print("error='FAILED HTTP REQUEST'")
        return
    if response.status_code != 200:
        eprint(response.content)
        print("error='FAILED HTTP CODE ({0})'".format(response.status_code))
        return
    
    # parse & validate data
    try:
        jData = json.loads(response.content)
        if len(jData['item_details']) == 0:
            print("error='MISSING ITEM'")
            return
        if len(jData['ln_invoices']) > 1:
            print("error='MORE THEN ONE INVOICE'")
            return
    except Exception as e:
        eprint(e)
        print("error='FAILED JSON PARSING'")
        return

    return jData 
开发者ID:rootzoll,项目名称:raspiblitz,代码行数:33,代码来源:blitz.ip2tor.py

示例14: apiGetBridgeStatus

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
def apiGetBridgeStatus(session, shopurl, bridgeid):

    print("# apiGetBridgeStatus")

    # make HTTP request
    try:
        response = session.get("{0}/api/v1/public/tor_bridges/{1}/".format(shopurl,bridgeid))
    except Exception as e:
        eprint(e)
        print("error='FAILED HTTP REQUEST'")
        return
    if response.status_code != 200:
        eprint(response.content)
        print("error='FAILED HTTP CODE ({0})'".format(response.status_code))
        return
    # parse & validate data
    try:
        jData = json.loads(response.content)
        if len(jData['id']) == 0:
            print("error='ID IS MISSING'")
            return
    except Exception as e:
        eprint(e)
        print("error='FAILED JSON PARSING'")
        return

    return jData 
开发者ID:rootzoll,项目名称:raspiblitz,代码行数:29,代码来源:blitz.ip2tor.py

示例15: load_toml_path_config

# 需要导入模块: import toml [as 别名]
# 或者: from toml import loads [as 别名]
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', 'policy_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),
        policy_dir=toml_config.get('policy_dir', None)
    )

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


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