我有一个项目需要读取记录良好的yaml
文件,修改几个值,然后将其写回。麻烦的是,yaml-cpp
完全删除了所有评论,并且"吃掉了#34;他们。有趣的是,YAML::Emitter
类允许用户在输出中添加注释。有没有办法保留输入中的注释并将它们写回到我没有看到的库中?因为现在看来,我无法使用YAML::Parser
类(使用YAML::Scanner
类,其中评论本身实际上已被“吃掉”#34;)
答案 0 :(得分:1)
注释是演示文稿的详细信息,不得对序列化树或表示图
产生任何影响
所以你需要使解析器不兼容以保留注释,如果yaml-cpp这样做,他们应该在文档中明确说明。
我在ruamel.yaml中为Python做了这个。如果从您的C ++程序中嵌入和调用Python是可以接受的,那么您可以执行以下操作(我在Linux Mint下使用Python 3.5):
pythonyaml.cpp
:
#include <Python.h>
int
update_yaml(const char*yif, const char *yof, const char* obj_path, int val)
{
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs, *pValue;
const char *modname = "update_yaml";
const char *lus = "load_update_save";
Py_Initialize();
// add current directory to search path
PyObject *sys_path = PySys_GetObject("path");
PyList_Append(sys_path, PyUnicode_FromString("."));
pName = PyUnicode_DecodeFSDefault(modname);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, lus);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(4);
PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(yif));
PyTuple_SetItem(pArgs, 1, PyUnicode_FromString(yof));
PyTuple_SetItem(pArgs, 2, PyUnicode_FromString(obj_path));
PyTuple_SetItem(pArgs, 3, PyLong_FromLong(val));
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Old value: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", lus);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", modname);
return 1;
}
Py_Finalize();
return 0;
}
int
main(int argc, char *argv[])
{
const char *yaml_in_file = "input.yaml";
const char *yaml_out_file = "output.yaml";
update_yaml(yaml_in_file, yaml_out_file, "abc.1.klm", 42);
}
创建一个Makefile
(修改Python3.5安装的路径,需要安装头文件,如果从源代码编译正常,否则需要安装软件包python3-dev
):
echo -e "SRC:=pythonyaml.cpp\n\ncompile:\n\tgcc \$(SRC) $(/opt/python/3.5/bin/python3-config --cflags --ldflags | tr --delete '\n' | sed 's/-Wstrict-prototypes//') -o pythonyaml" > Makefile
使用make
编译程序。
创建update_yaml.py
将由pythonyaml
加载:
# coding: utf-8
import traceback
import ruamel.yaml
def set_value(data, key_list, value):
"""key list is a set keys to access nested dict and list
dict keys are assumed to be strings, keys for a list must be convertable to integer
"""
key = key_list.pop(0)
if isinstance(data, list):
key = int(key)
item = data[key]
if len(key_list) == 0:
data[key] = value
return item
return set_value(item, key_list, value)
def load_update_save(yaml_in, yaml_out, obj_path, value):
try:
if not isinstance(obj_path, list):
obj_path = obj_path.split('.')
with open(yaml_in) as fp:
data = ruamel.yaml.round_trip_load(fp)
res = set_value(data, obj_path.split('.'), value)
with open(yaml_out, 'w') as fp:
ruamel.yaml.round_trip_dump(data, fp)
return res
except Exception as e:
print('Exception', e)
traceback.print_exc() # to get some useful feedback if your python has errors
创建input.yaml
:
abc:
- zero-th item of list
- klm: -999 # the answer?
xyz: last entry # another comment
如果您在python3.5中安装了ruamel.yaml
并运行./python_yaml
,则会打印Old value: -999
,新文件output.yaml
将包含:
abc:
- zero-th item of list
- klm: 42 # the answer?
xyz: last entry # another comment
42
只有两个字符,其中-999
有四个,但评论仍然与其下方的评论一致abc.1.klm
在C ++中,并将其作为第三个参数传递给load_update_save()
。在这种情况下,您可以拥有除字符串之外的其他项的键,或者包含点PyLong_FromLong
为第四个参数)的硬编码假设。 python程序不需要更新。ruamel.yaml
更改来自python文件的评论