本文整理匯總了Python中yaml.CLoader方法的典型用法代碼示例。如果您正苦於以下問題:Python yaml.CLoader方法的具體用法?Python yaml.CLoader怎麽用?Python yaml.CLoader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類yaml
的用法示例。
在下文中一共展示了yaml.CLoader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _download_results
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def _download_results(config, _blob_client, out_path, count, ptrn=FOLD_FILE_PATTERN):
pathlib.Path(config.BATCH_DIRECTORY).mkdir(parents=True, exist_ok=True)
blob_names = [b.name for b in _blob_client.list_blobs(config.CONTAINER_NAME)]
results = []
for i in range(count):
blob_name = ptrn.format(i)
if not blob_name in blob_names:
raise RuntimeError("incomplete blob set: missing blob {}".format(blob_name))
out_path = os.path.join(config.BATCH_DIRECTORY, blob_name)
with _blob_client.get_blob_to_stream(
config.CONTAINER_NAME, blob_name, out_path
) as blob:
results[i] = load(blob, Loader=Loader)
return results
示例2: get_config
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def get_config(infile):
"""
read in the contents of the inputs yaml file
"""
with open(infile, "r") as fp:
config = load(fp, Loader=Loader)
try:
v_pen = tuple(config["v_pen"])
except TypeError:
v_pen = (config["v_pen"],)
try:
w_pen = tuple(config["w_pen"])
except TypeError:
w_pen = (config["w_pen"],)
return v_pen, w_pen, config
示例3: is_roll_back
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def is_roll_back(update: dict):
"""
check if the new update is actually a rollback one
"""
codename = update['codename']
version = update['version']
filename = update['filename']
branch = get_branch(version)
rom_type = get_type(filename).lower()
try:
with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'r') as yaml_file:
data = yaml.load(yaml_file, Loader=yaml.CLoader)
versions = list(data[codename].keys())
return bool(version in versions)
except FileNotFoundError:
return False
示例4: archive
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def archive(update: dict):
"""Append new update to the archive"""
codename = update['codename']
link = update['download']
version = update['version']
branch = get_branch(version)
rom_type = 'recovery' if update['filename'].endswith('.zip') else 'fastboot'
try:
with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'r') as yaml_file:
data = yaml.load(yaml_file, Loader=yaml.CLoader)
data[codename].update({version: link})
data.update({codename: data[codename]})
with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'w') as output:
yaml.dump(data, output, Dumper=yaml.CDumper)
except FileNotFoundError:
data = {codename: {version: link}}
with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'w') as output:
yaml.dump(data, output, Dumper=yaml.CDumper)
示例5: merge_archive
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def merge_archive():
"""
merge all archive yaml files into one file
"""
print("Creating archive YAML files")
for name in ['stable_recovery', 'stable_fastboot', 'weekly_recovery', 'weekly_fastboot']:
yaml_files = [x for x in sorted(glob(f'archive/{name}/*.yml'))
if not x.endswith('recovery.yml')
and not x.endswith('fastboot.yml')]
yaml_data = []
for file in yaml_files:
with open(file, "r") as yaml_file:
yaml_data.append(yaml.load(yaml_file, Loader=yaml.CLoader))
with open(f'archive/{name}/{name}', "w") as output:
yaml.dump(yaml_data, output, Dumper=yaml.CDumper)
if path.exists(f'archive/{name}/{name}'):
rename(f'archive/{name}/{name}', f'archive/{name}/{name}.yml')
示例6: __init__
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def __init__(self,filename=None):
self.joint_p = []
self.joint_v = []
self.joint_t = []
self.gripper_cmd = []
self.gripper_t = []
self.tform = {}
self.world_t = []
if not filename==None:
stream = file(filename,'r')
demo = yaml.load(stream,Loader=Loader)
self.joint_p = demo.joint_p
self.joint_v = demo.joint_v
self.joint_t = demo.joint_t
self.gripper_cmd = demo.gripper_cmd
self.tform = demo.tform
self.world_t = demo.world_t
示例7: parse_yaml_file
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def parse_yaml_file(file: TextIOWrapper) -> Optional[dict]:
"""Parses a YAML file and returns a nested dictionary containing its contents.
:param file: Handle of file to parse
:return: Parsed file contents"""
try:
# Parses the YAML file into a dict
return load(file, Loader=Loader)
except YAMLError as exc:
logging.critical("Could not parse YAML file %s", file.name)
if hasattr(exc, 'problem_mark'):
# Tell user exactly where the syntax error is
mark = exc.problem_mark
logging.error("Error position: (%s:%s)",
mark.line + 1, mark.column + 1)
else:
logging.error("Error: %s", exc)
return None
# PyYAML Reference: http://pyyaml.org/wiki/PyYAMLDocumentation
示例8: parse_yaml
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def parse_yaml(filename: str) -> Optional[dict]:
"""Parses a YAML file and returns a nested dictionary containing its contents.
:param filename: Name of YAML file to parse
:return: Parsed file contents"""
try:
# Enables use of stdin if '-' is specified
with sys.stdin if filename == '-' else open(filename) as f:
try:
# Parses the YAML file into a dict
return load(f, Loader=Loader)
except YAMLError as exc:
logging.critical("Could not parse YAML file %s", filename)
if hasattr(exc, 'problem_mark'):
# Tell user exactly where the syntax error is
mark = exc.problem_mark
logging.error("Error position: (%s:%s)",
mark.line + 1, mark.column + 1)
else:
logging.error("Error: %s", exc)
return None
except FileNotFoundError:
logging.critical("Could not find YAML file for parsing: %s", filename)
return None
示例9: loads
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def loads(self, s, force_document_comment_to_first_entry=False, with_comments=False):
if not with_comments: # don't care about first comment if we don't care about coments globaly
force_document_comment_to_first_entry = False
if force_document_comment_to_first_entry:
s = '____useless_property: true\n' + s
yamllib = self.get_yaml_lib(with_comments)
if with_comments:
data = yamllib.round_trip_load(s)
else:
# The yaml lib do not manage loads, so need to fake it first
StringIO = libstore.get_StringIO_unicode_compatible()
fake_file = StringIO(s) # unicode_to_bytes(s))
if simple_yaml_loader is not None:
data = yamllib.load(fake_file, Loader=simple_yaml_loader)
else:
data = yamllib.round_trip_load(s)
if force_document_comment_to_first_entry:
del data['____useless_property']
return data
示例10: create_papers
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def create_papers(srcdir, clean=False):
"""Creates page stubs for all papers in the Anthology."""
log.info("Creating stubs for papers...")
if not check_directory("{}/content/papers".format(srcdir), clean=clean):
return
# Go through all paper volumes
for yamlfile in tqdm(glob("{}/data/papers/*.yaml".format(srcdir))):
log.debug("Processing {}".format(yamlfile))
with open(yamlfile, "r") as f:
data = yaml.load(f, Loader=Loader)
# Create a paper stub for each entry in the volume
for anthology_id, entry in data.items():
paper_dir = "{}/content/papers/{}".format(srcdir, anthology_id.split("-")[0])
if not os.path.exists(paper_dir):
os.makedirs(paper_dir)
with open("{}/{}.md".format(paper_dir, anthology_id), "w") as f:
print("---", file=f)
yaml.dump(
{"anthology_id": anthology_id, "title": entry["title"]},
default_flow_style=False,
stream=f,
)
print("---", file=f)
示例11: create_people
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def create_people(srcdir, clean=False):
"""Creates page stubs for all authors/editors in the Anthology."""
log.info("Creating stubs for people...")
if not check_directory("{}/content/people".format(srcdir), clean=clean):
return
for yamlfile in tqdm(glob("{}/data/people/*.yaml".format(srcdir))):
log.debug("Processing {}".format(yamlfile))
with open(yamlfile, "r") as f:
data = yaml.load(f, Loader=Loader)
# Create a page stub for each person
for name, entry in data.items():
person_dir = "{}/content/people/{}".format(srcdir, name[0])
if not os.path.exists(person_dir):
os.makedirs(person_dir)
yaml_data = {"name": name, "title": entry["full"], "lastname": entry["last"]}
with open("{}/{}.md".format(person_dir, name), "w") as f:
print("---", file=f)
# "lastname" is dumped to allow sorting by it in Hugo
yaml.dump(yaml_data, default_flow_style=False, stream=f)
print("---", file=f)
return data
示例12: create_sigs
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def create_sigs(srcdir, clean=False):
"""Creates page stubs for all SIGs in the Anthology."""
yamlfile = "{}/data/sigs.yaml".format(srcdir)
log.debug("Processing {}".format(yamlfile))
with open(yamlfile, "r") as f:
data = yaml.load(f, Loader=Loader)
log.info("Creating stubs for SIGs...")
if not check_directory("{}/content/sigs".format(srcdir), clean=clean):
return
# Create a paper stub for each SIGS (e.g. SIGMORPHON)
for sig, sig_data in data.items():
sig_str = sig_data["slug"]
with open("{}/content/sigs/{}.md".format(srcdir, sig_str), "w") as f:
print("---", file=f)
yaml.dump(
{
"acronym": sig,
"short_acronym": sig[3:] if sig.startswith("SIG") else sig,
"title": sig_data["name"],
},
default_flow_style=False,
stream=f,
)
print("---", file=f)
示例13: load_results_sixd17
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def load_results_sixd17(path):
"""
Loads 6D object pose estimates from a file.
:param path: Path to a file with poses.
:return: List of the loaded poses.
"""
with open(path, "r") as f:
res = yaml.load(f, Loader=yaml.CLoader)
if not res["ests"] or res["ests"] == [{}]:
res["ests"] = []
else:
for est in res["ests"]:
est["R"] = np.array(est["R"]).reshape((3, 3))
est["t"] = np.array(est["t"]).reshape((3, 1))
if isinstance(est["score"], str):
if "nan" in est["score"]:
est["score"] = 0.0
else:
raise ValueError("Bad type of score.")
return res
示例14: load_app_from_config
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def load_app_from_config(path):
"""
Generate app directly from config file, bypassing command line settings (useful for testing in ipython)
"""
Setting.generate_missing_shorthands()
defaults = Setting.generate_defaults_dict()
if osp.isfile(path):
file_stream = open(path, "r", encoding="utf-8")
config_defaults = load(file_stream, Loader=Loader)
file_stream.close()
for key, value in config_defaults.items():
defaults[key] = value
else:
raise ValueError("Settings file not found at: {0:s}".format(path))
args = ap.Namespace()
for key, value in defaults.items():
args.__dict__[key] = value
app = StereoMatcherApp(args)
return app
示例15: load_app_from_config
# 需要導入模塊: import yaml [as 別名]
# 或者: from yaml import CLoader [as 別名]
def load_app_from_config(path):
"""
Generate app directly from config file, bypassing command line settings (useful for testing in ipython)
"""
Setting.generate_missing_shorthands()
defaults = Setting.generate_defaults_dict()
if osp.isfile(path):
file_stream = open(path, "r", encoding="utf-8")
config_defaults = load(file_stream, Loader=Loader)
file_stream.close()
for key, value in config_defaults.items():
defaults[key] = value
else:
raise ValueError("Settings file not found at: {0:s}".format(path))
args = ap.Namespace()
for key, value in defaults.items():
args.__dict__[key] = value
if args.unsynced:
app = ApplicationUnsynced(args)
else:
app = ApplicationSynced(args)
return app