YAML ファイルの取り扱い
PyYAML Documentation
読込み
import yaml
file = 'testbed_topology.yaml'
with open(file, 'r') as f:
topology = yaml.safe_load(f)
print(type(topology))
# <class 'dict'> 辞書型のオブジェクト
書き出し
import yaml
data = {
'theme': {
'name': 'material'
}
}
with open('mkdocs.yml', 'w') as f:
yaml.dump(data, f)
parse nest yaml
import re,yaml
from pprint import pprint
datafile = './trigger_datafile.yaml'
with open(datafile, 'r',encoding="utf-8") as f:
datafile = yaml.safe_load(f)
def get_procedure(datafile):
result =[]
# 以下の処理を再帰的に実施
if isinstance(datafile, str):
datafile = select_item(datafile)
if datafile != None:
result.append(datafile)
elif isinstance(datafile, int):
result.append(f"sleep time : {datafile}")
elif isinstance(datafile, list):
for item in datafile:
result += get_procedure(item)
elif isinstance(datafile, dict):
for value in datafile.values():
result += get_procedure(value)
return result
def select_item(arg):
if arg == 'failed':
return None
elif arg == 'device':
return None
elif arg == '%VARIABLES{device}':
return None
elif re.search(r'\!= passed',arg):
return None
else:
return arg
# 不要なセクション・文字列を削除
def del_nouses(arg):
for i in arg:
if re.search(r'\!\!\! 0',str(i)):
del arg[:arg.index(i)]
break
def del_section(arg):
for i in arg:
if re.search(r'\!\!\! \d+',str(i)):
if arg[arg.index(i)-1] == '%VARIABLES{device_list}':
del arg[arg.index(i)-1]
return arg
return del_section(arg)
result = del_nouses(get_procedure(datafile))
pprint(result)