【发布时间】:2019-06-28 19:09:16
【问题描述】:
我看到 Python 曾经为 C/C++ 头文件和源文件生成大量代码。通常,存储参数的输入文件是 JSON 或 YAML 格式,尽管我看到的大部分是 YAML。但是,为什么不直接使用 Python 文件呢?在这种情况下为什么要使用 YAML?
这也让我想到:由于 Python 是一种脚本语言,它的文件,当只包含数据和数据结构时,实际上可以与 XML、JSON、YAML 等一样使用。人们会这样做吗?有没有好的用例?
如果我想将配置文件导入 C 或 C++ 程序怎么办?进入 Python 程序呢?在 Python 案例中,在我看来,使用 YAML 毫无意义,因为您可以将配置参数和变量存储在纯 Python 文件中。在 C 或 C++ 的情况下,在我看来,您仍然可以将数据存储在 Python 文件中,然后只需导入一个 Python 脚本并在构建过程中为您自动生成头文件和源文件。同样,在这种情况下,也许根本不需要 YAML 或 JSON。
想法?
以下是在 YAML 文件中存储一些嵌套键/值哈希表对的示例:
my_params.yml:
---
dict_key1:
dict_key2:
dict_key3a: my string message
dict_key3b: another string message
在纯 Python 文件中也是如此:
my_params.py
>data = {
"dict_key1": {
"dict_key2": {
"dict_key3a": "my string message",
"dict_key3b": "another string message",
}
}
}
读取 YAML 和 Python 数据并打印出来:
import_config_file.py:
import yaml # Module for reading in YAML files
import json # Module for pretty-printing Python dictionary types
# See: https://stackoverflow.com/a/34306670/4561887
# 1) import .yml file
with open("my_params.yml", "r") as f:
data_yml = yaml.load(f)
# 2) import .py file
from my_params import data as data_py
# OR: Alternative method of doing the above:
# import my_params
# data_py = my_params.data
# 3) print them out
print("data_yml = ")
print(json.dumps(data_yml, indent=4))
print("\ndata_py = ")
print(json.dumps(data_py, indent=4))
使用json.dumps的参考:https://stackoverflow.com/a/34306670/4561887
运行python3 import_config_file.py的示例输出:
data_yml =
{
"dict_key1": {
"dict_key2": {
"dict_key3a": "my string message",
"dict_key3b": "another string message"
}
}
}
data_py =
{
"dict_key1": {
"dict_key2": {
"dict_key3a": "my string message",
"dict_key3b": "another string message"
}
}
}
【问题讨论】:
-
尝试编辑
my_params.py并以编程方式保存新配置。 -
jupyter/ipython使用py配置文件,ipython.readthedocs.io/en/stable/development/config.html。默认版本主要由注释代码组成,建议行取消注释并添加自定义值。
标签: python json xml configuration yaml