yaml学习

本文介绍了yaml的安装过程,详细讲解了如何创建.yaml或.yml配置文件,并通过实例展示了字典和列表的使用。同时,文章还探讨了yaml文件的封装技巧,特别是针对日志记录的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、yaml的安装:

pip install pyyaml

二、yaml配置文件的创建:

创建文件时以.yaml后缀名结束或者以.yml后缀名结束

三、yaml文件例子

1、字典

log:
  logger_name: "python"
  logger_level: "DEBUG"
  stream_level: "DEBUG"
  file_level: "INFO"
  filepath: "pythonlog.txt"

2、列表

study:
  - hello
  - world
  - python

注:冒号后面要记得加空格(logger_name:空格"python")

四、yaml文件封装

import yaml

#读取yaml配置文件

def read_yaml(filepath):
    with open(filepath,encoding="utf-8") as f:
        conf=yaml.load(f,Loader=yaml.SafeLoader)
        return conf


#写入数据到yaml配置文件

def write_yaml(filepath,data):
    with open(filepath,"a",encoding="utf-8") as f:
        yaml.dump(data,f)

#调试本程序
if __name__ =="__main__":
    con=read_yaml("config.yaml")
    print(con)

    write_yaml("config.yaml","testdata")

五、使用yaml封装日志记录

import logging

"""
使用yaml封装日志记录
"""
#导入已封装的读取yaml配置文件的函数
from study_yaml.yaml_handle import read_yaml

conf=read_yaml("config.yaml")
logconf=conf["log"]   #如果未将conf["log"]赋值,则下面的参数需要写成logger_name=conf["log"]["logger_name"]

def record_logging(logger_name=logconf["logger_name"],logger_level=logconf["logger_level"],stream_level=logconf["stream_level"],file_level=logconf["file_level"],filepath=logconf["filepath"]):
        # 初始化收集器
        logger = logging.getLogger(logger_name)
        logger.setLevel(logger_level)

        # 初始化处理器,输出日志到控制台
        stream_handle = logging.StreamHandler()
        stream_handle.setLevel(stream_level)

        # 将处理器添加到收集器里
        logger.addHandler(stream_handle)

        # 设置输出日志格式,包括时间,报错的文件名,行号,错误等级及错误信息
        fm = logging.Formatter("%(asctime)s---%(filename)s---%(lineno)d---%(levelname)s---%(message)s")
        stream_handle.setFormatter(fm)

        # 如果文件路径不为空,就输出日志到文本文件
        if filepath:
             # 初始化处理器,输出日志到文本文件
             file_handle = logging.FileHandler(filepath, encoding="UTF-8")
             file_handle.setLevel(file_level)
             file_handle.setFormatter(fm)
             logger.addHandler(file_handle)

        return logger

if __name__ == '__main__':
    logger = record_logging()    #不传参按照默认的执行
    # logger=record_logging(stream_level="ERROR",file_level="CRITICAL",filepath="log.txt")
    logger.debug("debug信息")
    logger.info("info信息")
    logger.warning("warning信息")
    logger.error("error信息")
    logger.critical("critical信息")

 

 

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值