本文整理汇总了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
示例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)
示例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
示例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
示例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
示例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
示例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"])
示例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())
示例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
示例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()
示例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']
示例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']
示例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
示例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
示例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