本文整理汇总了Python中pytoml.load函数的典型用法代码示例。如果您正苦于以下问题:Python load函数的具体用法?Python load怎么用?Python load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _load_configs
def _load_configs(path) -> dict:
confs = {}
gui_confs = {}
for item in os.listdir(path):
if os.path.isdir(os.path.join(path, item)):
name_short = ""
try:
with open(os.path.join(path, item, "config.toml")) as conffile:
config = toml.load(conffile)
name_short = config["name_short"]
confs[name_short] = config
except IOError:
continue
try:
with open(os.path.join(path, item, "gui_config.toml")) as conffile:
config = toml.load(conffile)
gui_confs[name_short] = config
except IOError:
print("Failed to open GUI conf file.")
continue
return confs, gui_confs
开发者ID:tzaeru,项目名称:NWNLauncher,代码行数:25,代码来源:config.py
示例2: _main
def _main():
ap = argparse.ArgumentParser()
ap.add_argument('-d', '--dir', action='append')
ap.add_argument('testcase', nargs='*')
args = ap.parse_args()
if not args.dir:
args.dir = [os.path.join(os.path.split(__file__)[0], 'toml-test/tests')]
succeeded = []
failed = []
for path in args.dir:
if not os.path.isdir(path):
print('error: not a dir: {}'.format(path))
return 2
for top, dirnames, fnames in os.walk(path):
for fname in fnames:
if not fname.endswith('.toml'):
continue
if args.testcase and not any(arg in fname for arg in args.testcase):
continue
parse_error = None
try:
with open(os.path.join(top, fname), 'rb') as fin:
parsed = toml.load(fin)
except toml.TomlError:
parsed = None
parse_error = sys.exc_info()
else:
dumped = toml.dumps(parsed)
parsed2 = toml.loads(dumped)
if parsed != parsed2:
failed.append((fname, None))
continue
with open(os.path.join(top, fname), 'rb') as fin:
parsed = toml.load(fin, translate=_testbench_literal)
try:
with io.open(os.path.join(top, fname[:-5] + '.json'), 'rt', encoding='utf-8') as fin:
bench = json.load(fin)
except IOError:
bench = None
if parsed != adjust_bench(bench):
failed.append((fname, parsed, bench, parse_error))
else:
succeeded.append(fname)
for f, parsed, bench, e in failed:
print('failed: {}\n{}\n{}'.format(f, json.dumps(parsed, indent=4), json.dumps(bench, indent=4)))
if e:
traceback.print_exception(*e)
print('succeeded: {}'.format(len(succeeded)))
return 1 if failed or not succeeded else 0
开发者ID:njsmith,项目名称:pytoml,代码行数:58,代码来源:test.py
示例3: persistent_loop
def persistent_loop(f, path, initialstate=()):
def load():
from pickle import load as _load
with open(path, 'rb') as f:
return _load(f)
def save(st):
from pickle import dump
from os import rename
tmppath = path + '.tmp'
with open(tmppath, 'wb') as f:
dump(st, f)
rename(tmppath, path)
if not exists(path):
save(initialstate)
while True:
state = load()
if isinstance(state, EndLoop):
return state.value
state = f(*state)
# Support returning just EndLoop (without instantiation)
if state is EndLoop:
state = EndLoop(None)
save(state)
开发者ID:ExpHP,项目名称:vaspmd,代码行数:29,代码来源:search.py
示例4: _load_local_version_data
def _load_local_version_data() -> dict:
if os.path.isfile(path_finder.get_local_version_data_path()) != True:
_create_dummy_version_data_file()
with open(path_finder.get_local_version_data_path()) as local_version_data_file:
data_as_dict = toml.load(local_version_data_file)
return data_as_dict
开发者ID:tzaeru,项目名称:NWNLauncher,代码行数:7,代码来源:dependency_manager.py
示例5: Parse
def Parse(self, path = 'COMAKE'):
try:
with codecs.open(path, 'r', 'utf-8') as f:
comake = toml.load(f)
except toml.TomlError as e:
print RedIt("[ERROR] {} load failed".format(path))
raise InvalidComake("COMAKE has something wrong")
else:
if 'output' in comake.keys():
size = len(comake['output'])
for i in range(size):
sources_set = _parsePath(comake['output'][i]['sources'])
comake['output'][i]['sources'] = ' '.join(sources_set)
headers_set = _parsePath(comake['output'][i]['headers'])
comake['output'][i]['headers'] = ' '.join(headers_set)
comake['output'][i]['a'] = comake['output'][i]['a'].strip()
comake['output'][i]['so'] = comake['output'][i]['so'].strip()
self.total_sources.update(sources_set)
self.total_headers.update(headers_set)
comake['total_sources'] = ' '.join(self.total_sources)
comake['total_headers'] = ' '.join(self.total_headers)
comake['include_path'] = ' '.join(['-I' + s for s in comake['include_path'].split()])
comake['library_path'] = ' '.join(['-L' + s for s in comake['library_path'].split()])
self.comake = comake
if 'use_local_makefile' not in self.comake.keys():
self.comake['use_local_makefile'] = 0
if 'use_local_copy' not in self.comake.keys():
self.comake['use_local_copy'] = 1
self._parseDepPath()
return self.comake
开发者ID:boully,项目名称:comake,代码行数:35,代码来源:ParseComake.py
示例6: iter_code_lessons
def iter_code_lessons(path='.', unit_glob='unit-*', grep=None, units=None,
lesson_glob='lesson-*', rmotr_toml_name='.rmotr'):
grep = grep or []
p = Path(path)
for unit in p.glob(unit_glob):
unit_number = _get_unit_number(unit.name)
if units and unit_number not in units:
continue
for lesson_path in unit.glob(lesson_glob):
rmotr_toml = lesson_path / rmotr_toml_name
if not rmotr_toml.exists():
raise InvalidLessonException(
("Lessons must contain a .rmotr file. "
"Lesson {} doesn't contain any").format(lesson_path.name))
with rmotr_toml.open() as rmotr_f:
lesson_data = toml.load(rmotr_f)
lesson_name = lesson_data['name']
if lesson_data['type'] == 'assignment':
add_lesson = True
for keyword in grep:
if keyword not in lesson_name.lower():
add_lesson = False
break
if not add_lesson:
continue
logger.info("Added lesson", extra={'lesson_name': lesson_name})
yield Lesson(name=lesson_name,
uuid=lesson_data['uuid'],
path=lesson_path,
_lesson_data=lesson_data)
开发者ID:rmotr-curriculum,项目名称:pyp-class,代码行数:32,代码来源:run_tests.py
示例7: parse_settings_toml
def parse_settings_toml(config_filepath, defaults=None):
"""
Grabs key/value pairs from a TOML format config file,
returns an argparse options-style data container object
with the config. A dictionary can be provided with defaults,
which any option specified in the config file will override.
(The defaults dictionary might can be generated via passing a
pre-configured argparse.ArgumentParser into get_parser_defaults)
:param config_filepath: The path to a TOML config file.
:type config_filepath: basestring
:param defaults: A dictionary of defaults
:type defaults: dict
:return: A data container object of config options.
:rtype: object
"""
if defaults is None:
defaults = dict()
else:
# Copy
defaults = dict(defaults)
with open(config_filepath, 'r') as f:
config = toml.load(f)
config = recursive_dict_merge(defaults, config)
config = AttrDict(config)
return config
开发者ID:mytardis,项目名称:mytardis_ngs_ingestor,代码行数:30,代码来源:config_helper.py
示例8: main
def main():
''' Run test '''
config_filename = "load.toml"
if len(sys.argv) > 1:
config_filename = sys.argv[1]
filename_components = config_filename.split('.')
if len(filename_components) > 1:
extension = filename_components[-1]
with open(config_filename, 'rb') as fin:
if extension == 'toml':
config = pytoml.load(fin)
elif extension in ['yaml', 'yml']:
config = yaml.load(fin)
elif extension == 'json':
config = json.load(fin)
else:
print("Config file has unsupported format: %s" % extension)
else:
print(
"Config file should have one of the following extensions:"
" .toml, .json, .yaml")
return 1
init_logging()
lt = LoadTest(config)
lt.run_test()
开发者ID:direvius,项目名称:bfg,代码行数:27,代码来源:cli.py
示例9: read_conf
def read_conf(folder: Path) -> Dict[str, Any]:
conf_path = folder / CONF_NAME
if not conf_path.exists():
return {}
with open(conf_path, "rb") as fd:
return toml.load(fd)[_SECTION]
开发者ID:Azure,项目名称:azure-sdk-for-python,代码行数:7,代码来源:conf.py
示例10: load_settings_table
def load_settings_table(path):
"""Loads settings table into dict"""
try:
table_open_object = open(path, 'r')
except FileNotFoundError:
return None
table = pytoml.load(table_open_object)
return table
开发者ID:disloyalpick,项目名称:obozrenie,代码行数:8,代码来源:helpers.py
示例11: main
def main(options, args):
with open(options.config, "rb") as file:
toml = pytoml.load(file)
if not toml:
print("Bad toml file")
exit()
perform(toml, options)
开发者ID:healerkx,项目名称:PySQLKits,代码行数:8,代码来源:mysqlbatch.py
示例12: _main
def _main():
succeeded = []
failed = []
for top, dirnames, fnames in os.walk('.'):
for fname in fnames:
if not fname.endswith('.toml'):
continue
if sys.argv[1:] and not any(arg in fname for arg in sys.argv[1:]):
continue
parse_error = None
try:
with open(os.path.join(top, fname), 'rb') as fin:
parsed = toml.load(fin)
except toml.TomlError:
parsed = None
parse_error = sys.exc_info()
else:
dumped = toml.dumps(parsed)
parsed2 = toml.loads(dumped)
if parsed != parsed2:
failed.append((fname, None))
continue
with open(os.path.join(top, fname), 'rb') as fin:
parsed = toml.load(fin, translate=_testbench_literal)
try:
with io.open(os.path.join(top, fname[:-5] + '.json'), 'rt', encoding='utf-8') as fin:
bench = json.load(fin)
except IOError:
bench = None
if parsed != bench:
failed.append((fname, parsed, bench, parse_error))
else:
succeeded.append(fname)
for f, parsed, bench, e in failed:
print('failed: {}\n{}\n{}'.format(f, json.dumps(parsed, indent=4), json.dumps(bench, indent=4)))
if e:
traceback.print_exception(*e)
print('succeeded: {}'.format(len(succeeded)))
return 1 if failed else 0
开发者ID:ExpHP,项目名称:pytoml,代码行数:46,代码来源:test.py
示例13: _load_config
def _load_config(cls):
if cls._config is None:
cfg_path = os.path.expanduser('~/.cliist.toml')
if not os.path.isfile(cfg_path):
msg = "Configuration not found! Please run 'cliist configure'!"
raise ConfigurationError(msg)
with open(cfg_path) as fs:
cls._config = pytoml.load(fs)
return cls._config
开发者ID:boldfield,项目名称:cliist,代码行数:9,代码来源:config.py
示例14: parse_config
def parse_config(path):
if path is None or not os.path.exists(path):
return {}
try:
with io.open(path, 'r', encoding='utf-8') as stream:
return pytoml.load(stream)['general']
except IOError as error:
raise click.ClickException(error)
开发者ID:jvrsantacruz,项目名称:zonetimeline,代码行数:9,代码来源:ztl.py
示例15: generate
def generate(file):
'''
generates json from a toml
'''
input_file = file
output_file = input_file.replace('.toml', '.json')
with open(input_file, 'r') as tom, open(output_file, 'w') as son:
tom_tree = toml.load(tom)
son.write(json.dumps(tom_tree, indent=4, sort_keys=True))
开发者ID:kteza1,项目名称:switch-case,代码行数:9,代码来源:gen.py
示例16: main
def main(argv):
with open("Builder.toml", "r") as fin:
obj = toml.load(fin)
project = parse(obj)
transform(project, "Ninja")
if len(argv) > 1:
sys.exit(0)
build("Ninja")
开发者ID:NeuralSandwich,项目名称:Builder,代码行数:9,代码来源:Backend.py
示例17: load_blog
def load_blog(path):
from overviewer.models import BlogPost
import pytoml
with open(path) as f:
dat = pytoml.load(f)
for p in dat['posts']:
db.session.add(BlogPost(**p))
print('adding', p['title'])
db.session.commit()
开发者ID:overviewer,项目名称:Overviewer-Web,代码行数:9,代码来源:manage.py
示例18: parse_config
def parse_config():
with open('config.toml', 'rb') as fin:
obj = pytoml.load(fin)
if not obj['key']:
raise Exception('Key must be defined in config file')
if not 'start' in obj:
obj['start'] = 0
if not 'end' in obj:
obj['end'] = 10000
return obj
开发者ID:valenting,项目名称:presto,代码行数:10,代码来源:process_results.py
示例19: from_file
def from_file(cls, file):
"""Load settings from the given ``file`` and instantiate an
:class:`Configuration` instance from that.
:param file: the file object that contains TOML settings
:return: an instantiated configuration
:rtype: :class:`Configuration`
"""
return cls(load(file))
开发者ID:Kroisse,项目名称:settei,代码行数:10,代码来源:settei.py
示例20: loadConfig
def loadConfig(stages=[], configDir="./"):
for stage_name in stages:
configPath = os.path.join(configDir, "%s.toml" % (stage_name))
with open(configPath, 'rb') as fin:
config = toml.load(fin)
dump = json.dumps(config)
json_str = os.path.expandvars(dump)
config = json.loads(json_str)
env.roledefs[stage_name] = config
开发者ID:steffenmllr,项目名称:fabric-docker-microservices,代码行数:10,代码来源:fdm.py
注:本文中的pytoml.load函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论