You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Airflow的DAG.py中读取UI配置并传递给Python脚本参数

解决Airflow UI触发传参给Python脚本的问题

步骤1:修改DAG代码,支持读取触发配置

先补上原代码缺失的datetime导入,再通过Airflow模板语法读取UI触发时传入的配置参数,将其作为命令行参数传递给Python脚本。修改后的完整代码如下:

from airflow import DAG
from airflow.operators.bash import BashOperator
from datetime import datetime

dag = DAG(
    'Sample_DAG', 
    description='DAG for Sample run',
    schedule_interval='@monthly',
    start_date=datetime(2022, 11, 15),
    catchup=False,
)

bash_op = BashOperator(
    task_id="run_hello_file",
    # 用模板语法读取dag_run中的配置参数,作为Python脚本的参数
    bash_command= "python3.6 /path/to/hello_world.py {{ dag_run.conf.get('target_date', '') }}",
    dag=dag
)

步骤2:UI触发时传入日期参数

手动触发DAG时,在配置JSON输入框中传入日期参数,格式示例:

{"target_date": "2024-05-20"}

步骤3:Python脚本接收参数

修改hello_world.py,通过sys.argv读取命令行传入的日期参数:

import sys

if __name__ == "__main__":
    if len(sys.argv) > 1:
        target_date = sys.argv[1]
        print(f"Received target date: {target_date}")
        # 此处编写你的业务逻辑
    else:
        print("No date parameter provided")

补充说明

  • 用dag_run.conf.get('参数名', 默认值)的方式可以避免未传参时触发报错;如果要求必须传参,可直接用{{ dag_run.conf['target_date'] }},但未传参时任务会失败。
  • 若无需手动传参,想直接使用Airflow内置的执行日期,可替换模板变量为{{ execution_date }},无需在UI配置中传入参数。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:01:21