本文整理匯總了Python中toml.load方法的典型用法代碼示例。如果您正苦於以下問題:Python toml.load方法的具體用法?Python toml.load怎麽用?Python toml.load使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類toml
的用法示例。
在下文中一共展示了toml.load方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def main(configuration_path: Optional[str]) -> None:
"""Pinnwand pastebin software."""
from pinnwand import configuration
if configuration_path:
import toml
with open(configuration_path) as file:
configuration_file = toml.load(file)
for key, value in configuration_file.items():
setattr(configuration, key, value)
from pinnwand import database
database.Base.metadata.create_all(database._engine)
示例2: _prepare_pyproject_toml
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def _prepare_pyproject_toml(addon_dir, org, repo):
"""Inject towncrier options in pyproject.toml"""
pyproject_path = os.path.join(addon_dir, "pyproject.toml")
with _preserve_file(pyproject_path):
pyproject = {}
if os.path.exists(pyproject_path):
with open(pyproject_path) as f:
pyproject = toml.load(f)
if "tool" not in pyproject:
pyproject["tool"] = {}
pyproject["tool"]["towncrier"] = {
"template": _get_towncrier_template(),
"underlines": ["~"],
"title_format": "{version} ({project_date})",
"issue_format": _make_issue_format(org, repo),
"directory": "readme/newsfragments",
"filename": "readme/HISTORY.rst",
}
with open(pyproject_path, "w") as f:
toml.dump(pyproject, f)
yield
示例3: get_lib_name
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def get_lib_name(self):
""" Parse Cargo.toml to get the name of the shared library. """
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
name = cfg.get("package", {}).get("name")
if name is None:
raise Exception(
"Can not parse library name from Cargo.toml. "
"Cargo.toml missing value for 'name' key "
"in both the [package] section and the [lib] section"
)
name = re.sub(r"[./\\-]", "_", name)
return name
示例4: test_global
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def test_global(self, monkeypatch, tmpdir):
"""Tests that the functions integrate correctly when storing account
globally."""
with monkeypatch.context() as m:
m.setattr(conf, "user_config_dir", lambda *args: tmpdir)
conf.store_account(
authentication_token,
filename="config.toml",
location="user_config",
**DEFAULT_KWARGS
)
filepath = tmpdir.join("config.toml")
result = toml.load(filepath)
assert result == EXPECTED_CONFIG
示例5: load
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def load():
path = xdg.BaseDirectory.load_first_config(APP_NAME)
if not path:
return Config()
config_path = Path(path) / "config.toml"
if not config_path.exists():
return Config()
with config_path.open() as config_file:
try:
return Config.from_dict(toml.load(config_file))
except Exception:
logger.error(
"Could not load configuration file, ignoring",
path=config_path,
exc_info=True,
)
return Config()
示例6: from_toml
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def from_toml(cls: Type["Config"], filename: FilePath) -> "Config":
"""Load the configuration values from a TOML formatted file.
This allows configuration to be loaded as so
.. code-block:: python
Config.from_toml('config.toml')
Arguments:
filename: The filename which gives the path to the file.
"""
file_path = os.fspath(filename)
with open(file_path) as file_:
data = toml.load(file_)
return cls.from_mapping(data)
示例7: load_lockfile
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def load_lockfile(self, expand_env_vars=True):
with io.open(self.lockfile_location, encoding="utf-8") as lock:
j = json.load(lock)
self._lockfile_newlines = preferred_newlines(lock)
# lockfile is just a string
if not j or not hasattr(j, "keys"):
return j
if expand_env_vars:
# Expand environment variables in Pipfile.lock at runtime.
for i, _ in enumerate(j["_meta"]["sources"][:]):
j["_meta"]["sources"][i]["url"] = os.path.expandvars(
j["_meta"]["sources"][i]["url"]
)
return j
示例8: from_path
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def from_path(cls, path: Path, cache_url: str = '',
force_download: bool = False,
upgrade_lean: bool = True) -> 'LeanProject':
"""Builds a LeanProject from a Path object"""
try:
repo = Repo(path, search_parent_directories=True)
except InvalidGitRepositoryError:
raise InvalidLeanProject('Invalid git repository')
if repo.bare:
raise InvalidLeanProject('Git repository is not initialized')
is_dirty = repo.is_dirty()
try:
rev = repo.commit().hexsha
except ValueError:
rev = ''
directory = Path(repo.working_dir)
try:
config = toml.load(directory/'leanpkg.toml')
except FileNotFoundError:
raise InvalidLeanProject('Missing leanpkg.toml')
return cls(repo, is_dirty, rev, directory,
config['package'], config['dependencies'],
cache_url, force_download, upgrade_lean)
示例9: execute
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def execute(self, track):
configurations = list(self._expand_paths(track['configurations']))
versions = track['versions']
error = False
for version in versions:
self.log.info('# Version: ', version)
for c, configuration in enumerate(configurations):
self.log.info('## Starting Crate {0}, configuration: {1}'.format(
os.path.basename(version),
os.path.basename(configuration)
))
configuration = toml.load(os.path.join(self.track_dir, configuration))
crate_dir = get_crate(version, self.crate_root)
with CrateNode(crate_dir=crate_dir,
env=configuration.get('env'),
settings=configuration.get('settings')) as node:
node.start()
_error = self._execute_specs(track['specs'], node.http_url)
error = error or _error
return error
示例10: run_track
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def run_track(track,
result_hosts=None,
crate_root=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
failfast=False,
sample_mode='reservoir'):
"""Execute a track file"""
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
executor = Executor(
track_dir=os.path.dirname(track),
log=log,
result_hosts=result_hosts,
crate_root=crate_root,
fail_fast=failfast,
sample_mode=sample_mode
)
error = executor.execute(toml.load(track))
if error:
sys.exit(1)
示例11: test_config_from_toml
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def test_config_from_toml() -> None:
config = Config(Path(__file__).parent)
config.from_file("assets/config.toml", toml.load)
_check_standard_config(config)
示例12: from_directories
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def from_directories(cls, domain_dir=None, source_dir=None, analytics_dir=None, parent=None):
# type: (str, str, str, Configuration) -> Configuration
self = cls(parent=parent)
for domain_path in sorted(recursive_glob(domain_dir, "*.toml")):
self.add_domain(toml.load(domain_path))
for source_path in sorted(recursive_glob(source_dir, "*.toml")):
self.add_source(toml.load(source_path))
for analytic_path in sorted(recursive_glob(analytics_dir, "*.toml")):
self.add_analytic(toml.load(analytic_path), analytic_path)
return self
示例13: test_schema
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def test_schema(self):
schema = self.config.domain_schemas["security"].eql_schema
new_config = eqllib.Configuration(parent=self.config)
with schema:
paths = list(eqllib.utils.recursive_glob(self.analytics_path, "*.toml"))
paths.sort()
self.assertGreaterEqual(len(paths), 0)
for path in paths:
try:
new_config.add_analytic(toml.load(path))
except Exception:
print("Error loading file: {:s}".format(path), file=sys.stderr)
raise
示例14: update_pipfile
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def update_pipfile(stdout: bool):
import toml
project = Project()
LOGGER.debug(f"Processing {project.pipfile_location}")
top_level_packages, top_level_dev_packages = get_top_level_dependencies()
all_packages, all_dev_packages = get_all_packages()
pipfile = toml.load(project.pipfile_location)
configuration = [{'section': 'packages',
'top_level': top_level_packages,
'all_packages': all_packages},
{'section': 'dev-packages',
'top_level': top_level_dev_packages,
'all_packages': all_dev_packages}]
for config in configuration:
pipfile[config.get('section')] = {package.name: package.full_version
for package in _get_packages(config.get('top_level'),
config.get('all_packages'))}
if stdout:
LOGGER.debug(f"Outputting Pipfile on stdout")
print(toml.dumps(pipfile))
else:
LOGGER.debug(f"Outputting Pipfile top {project.pipfile_location}")
with open(project.pipfile_location, 'w') as writer:
writer.write(toml.dumps(pipfile))
return True
示例15: load_config
# 需要導入模塊: import toml [as 別名]
# 或者: from toml import load [as 別名]
def load_config(path):
"""Loads a dictionary from configuration file.
Args:
path: the path to load the configuration from.
Returns:
The configuration dictionary loaded from the file.
"""
return toml.load(path)