首页 > 编程语言 >python读取yaml配置文件的方法

python读取yaml配置文件的方法

时间:2024-04-25 14:34:40浏览次数:20  
标签:execute task 配置文件 schedule python celery yaml tasks

yaml简介
1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言。yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文件,看了yaml后,发现这个更直观,更方便,有点类似于json格式

2.yaml基本语法规则:

大小写敏感

使用缩进表示层级关系

缩进时不允许使用Tab键,只允许使用空格。

缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

#表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样

3.yaml支持的数据结构有三种:

对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

安装yaml
1.使用pip安装pyyaml模块

pip install pyyaml

安装之后-找zhoupan安装的 --20240425

 

 cfg.yaml文件

# celery config
backend: redis://127.0.0.1:6379
broker: redis://127.0.0.1:6380

# monitor config
tower_url : http://7.191.11.230:7894
chrono_url : http://10.169.50.233:8090

celery.py文件

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
celery配置文件
"""
import celery
from celery.schedules import crontab
from datetime import timedelta
import yaml
import os
from yaml import Loader

# 获取当前脚本所在文件夹路径
curPath = os.path.abspath(os.path.join(os.getcwd()))
# 获取yaml文件路径
yamlPath = os.path.join(curPath, "cfg.yaml")
print(yamlPath)
# open方法打开直接读出来
f = open(yamlPath, 'r', encoding='utf-8')
cfg = f.read()
d = yaml.load(cfg, Loader=Loader)  # 用load方法转字典

# 任务存储的数据库
backend = d.get('backend')
# 消息中间件
broker =  d.get('broker')

cel = celery.Celery('celery_demo',
                    backend=backend,
                    broker=broker,
                    # 包含以下两个任务文件,去相应的py文件中找任务,对多个任务做分类
                    include=[
                             'celery_tasks.task_execute_pre',
                             'celery_tasks.task_execute_post',
                             'celery_tasks.task_execute_main',
                             'celery_tasks.task_query',
                             'celery_tasks.task_status',
                             'celery_tasks.process_task'
                             ])

# 时区
cel.conf.timezone = 'Asia/Shanghai'
# 是否使用UTC
cel.conf.enable_utc = False

# 添加定时调度器
cel.conf.beat_schedule = {
    # 每一个元素都是一个定时任务,每一个元素的key是定时任务的名称
    'task_execute_main': {
            'task': 'celery_tasks.task_execute_main.execute_main_task',
            "schedule": timedelta(seconds=10),
            # 'schedule': crontab(minute="*/2"),
            'args': ('task_execute_main',)
        },
    'task_execute_post': {
        'task': 'celery_tasks.task_execute_post.execute_post_task',
        "schedule": timedelta(seconds=10),
        # 'schedule': crontab(minute="*/2"),
        'args': ('task_execute_post',)
    },
    'task_execute_pre': {
        'task': 'celery_tasks.task_execute_pre.execute_pre_task',
        "schedule": timedelta(seconds=10),
        # 'schedule': crontab(minute="*/2"),
        'args': ('task_execute_pre',)
    },
    'task_query': {
        'task': 'celery_tasks.task_query.parse_job_id',
        "schedule": timedelta(seconds=10),
        # 'schedule': crontab(minute="*/2"),
        'args': ('task_query',)
    },
    'task_status': {
        'task': 'celery_tasks.task_status.query_job_status',
        "schedule": timedelta(seconds=10),
        # 'schedule': crontab(minute="*/2"),
        'args': ('task_status',)
    },
    'process_task': {
        'task': 'celery_tasks.process_task.process_task',
        "schedule": timedelta(seconds=10),
        # 'schedule': crontab(minute="*/2"),
        'args': ('process_task',)
    }
}

 

 

参考博客:https://blog.csdn.net/zhusongziye/article/details/80024426

标签:execute,task,配置文件,schedule,python,celery,yaml,tasks
From: https://www.cnblogs.com/abc8023/p/18157641

相关文章

  • Python 彩色字体输出
    使用ANSI转译码给print添加颜色公式'\033[显示方式;字体颜色;背景色m输出内容\033[0m'公式参数解析\033:ANSI转义序列开始标识[:控制码用于控制字体方式、颜色、背景色(控制码对应参数值是唯一的所以仅设置一个参数时其他参数可以省略不用空占用)m:控制码结束标......
  • Python的Spacy
    spaCy是一个基于Python编写的开源自然语言处理库。基于自然处理领域的最新研究,spaCy提供了一系列高效且易用的工具,用于文本预处理、文本解析、命名实体识别、词性标注、句法分析和文本分类等任务。安装pipinstallspacy查看版本importspacyprint(spacy.__version__)......
  • python 一个开箱即用的多线程代码
    适合数据采集的多线程代码!#coding=utf-8#coding=gbk#coding=gb2312importrequestsimportthreadingimportqueuedefget_response(source):returnresponsedefdecode(source,response):##保存数据passdefmains():whileTrue:......
  • python读取xls表格中指定列或行范围的数据
    importxlrd#打开Excel文件workbook=xlrd.open_workbook('test01.xls')#获取第一个工作表worksheet=workbook.sheet_by_index(0)#指定的行区域#读取第(row_index_x+1)行中,第(start_cols+1)列至第end_cols列范围的数据start_cols=0#第(start_cols+1)列end_cols......
  • 【学习笔记】Python 使用 matplotlib 画图
    目录安装中文显示折线图、点线图柱状图、堆积柱状图坐标轴断点参考资料本文将介绍如何使用Python的matplotlib库画图,记录一些常用的画图demo代码安装#建议先切换到虚拟环境中pipinstallmatplotlib中文显示新版的matplotlib已经支持字体回退功能,因此可以直接设置......
  • AWS S3 Lambda Python脚本函数执行时报错AttributeError: module ‘PIL‘ has no attr
    背景代码示例如下importPILdefadd_image(self,tag,img,step):summary=Summary()bio=BytesIO()iftype(img)==str:img=PIL.Image.open(img)eliftype(img)==PIL.Image.Image:passelse:img=scipy.misc.......
  • python函数递归
    【递归】递归:是函数嵌套调用的一种特殊形式,也就是在调用一个函数的过程中右直接或是间接的调用到本身,然后一直循环deff1():print('一直是我')f1()f1()#调用本身,会死循环============================上述是直接调用间接调用  ================......
  • Python基础-模块和面向对象-shutil、re、bs4、requests模块
    概要:模块自定义模块(已经讲了)内置模块shutilre正则表达式第三方模块requests模块bs4模块面向对象:面向对象(Object-OrientedProgramming),简称OOP,是一种编程范式,它使用“对象”来设计软件,这些对象包含了数据(属性)和可以操作这些数据的方法。面向对象的核心......
  • Python基础-模块、Python操作excel
    模块和面向对象-day9今日概要模块自定义模块内置模块第三方模块[!Caution]这个地方讲的会比较多,而且有的东西网上搜不到!!!自动化办公相关模块--Excel和Word面向对象1.面向对象中的概念对象,什么是对象?比如说我桌子上好多东西,有铅笔、钢笔、圆珠笔,玻......
  • 交点法公路计算的一些相关方法函数(Python)
    1#弧度归一化2@staticmethod3defnormalize_radian(radian):4returnradian%tau56#获取坐标差7@staticmethod8defget_coord_diff(start_x,start_y,end_x,end_y):9returnend_x-start_x,end_y-st......