python实战: 解析yaml配置文件

一,生成目录和生成配置文件
创建目录和配置文件
[liuhongdi@img news]$ mkdir conf
[liuhongdi@img news]$ cd conf/
[liuhongdi@img conf]$ vi conf.yaml
[liuhongdi@img conf]$ more conf.yaml
查看文件内容:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
data_dev: host: 127.0.0.1 port: 3306 user: root password: password123 database: learning charset: utf8data_prd: host: 127.0.0.1 port: 3306 user: root password: password123 database: learning-prod charset: utf8 |
说明:刘宏缔的架构森林—专注it技术的博客,
网址:https://imgtouch.com
本文: https://blog.imgtouch.com/index.php/2024/02/19/jie-xi-yaml-pei-zhi-wen-jian/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,安装相关的库PyYAML
1,用pip安装:
(venv) [liuhongdi@img news]$ pip3 install PyYAML
Collecting PyYAML
Downloading PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (757 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 757.7/757.7 kB 12.6 kB/s eta 0:00:00
Installing collected packages: PyYAML
Successfully installed PyYAML-6.0.1
[notice] A new release of pip is available: 23.1.2 -> 24.0
[notice] To update, run: pip install --upgrade pip
安装完成后查看已安装库的版本:
(venv) [liuhongdi@img news]$ pip3 show PyYAML
Name: PyYAML
Version: 6.0.1
Summary: YAML parser and emitter for Python
Home-page: https://pyyaml.org/
Author: Kirill Simonov
Author-email: xi@resolvent.net
License: MIT
Location: /web/site/python/news/venv/lib/python3.11/site-packages
Requires:
Required-by:
三,编写代码读取yaml文件:
1,代码:
handle_yaml.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import yamlclass ConfYaml: # 操作conf.yaml文件的 def __init__(self, file): self.file = file def read_yaml(self, node='', encoding='utf-8'): """读取yaml数据""" with open(self.file, encoding=encoding) as f: conf = yaml.load(f.read(), Loader=yaml.FullLoader) if node == '': return conf else: return conf[node]if __name__ == '__main__': conf_file = "../../conf/conf.yaml" conf_yaml = ConfYaml(conf_file) node = 'data_prd' conf_node = conf_yaml.read_yaml(node) # 返回是字典格式,所以直接下标取数据 print(conf_node) host = conf_node['host'] port = conf_node['port'] user = conf_node['user'] pswd = conf_node['password'] base = conf_node['database'] char = conf_node['charset'] print("host:", host) print("port:", port) print("user:", user) print("password", pswd) print("database:", base) print("charset:", char) |
运行结果:
{'host': '127.0.0.1', 'port': 3307, 'user': 'root', 'password': 'password123', 'database': 'learning-prod', 'charset': 'utf8'}
host: 127.0.0.1
port: 3307
user: root
password password123
database: learning-prod
charset: utf8
浙公网安备 33010602011771号