Apache airlflow DAG无法导入本地modu

2024-05-16 22:49:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎不理解如何将模块导入apache airlow DAG定义文件。我想这样做是为了能够创建一个库,使使用类似设置的声明任务不那么冗长,例如。

下面是我能想到的最简单的例子,它复制了这个问题:我修改了airlow教程(https://airflow.apache.org/tutorial.html#recap),只需导入一个模块并从该模块运行一个定义。就像这样:

目录结构:

- dags/
-- __init__.py
-- lib.py
-- tutorial.py

教程.py:

"""
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

# Here is my added import
from lib import print_double

# And my usage of the imported def
print_double(2)

## -- snip, because this is just the tutorial code, 
## i.e., some standard DAG defintion stuff --

print_double只是一个简单的def,它将输入值乘以2,然后打印结果,但显然这根本不重要,因为这是一个导入问题。

我能够成功地按照教程文档运行airflow test tutorial print_date 2015-06-01dag运行,而且print_double成功。4按预期打印到控制台。一切看起来都很好。

然后我进入web用户界面,受到Broken DAG: [/home/airflow/airflow/dags/tutorial.py] No module named 'lib'的欢迎。取消暂停dag并尝试使用UI手动运行会导致“运行”状态,但它不会成功或失败。它只是永远坐在“奔跑”上。我可以想排多少就排多少,但他们都只是坐在“运行”状态。

我已经检查了气流日志,没有看到任何有用的调试信息。

那我错过了什么?


Tags: 模块thefrompyimport定义libapache
2条回答

您使用的是Airflow 1.9.0吗?这个可能在那里被修复。

这个问题是由气流加载dag的方式引起的:它不仅仅将dag作为普通python模块导入,因为它希望能够在不重新启动进程的情况下重新加载dag。因此.不在python搜索路径中。

如果1.9.0没有解决这个问题,最简单的更改是在启动脚本中放入export PYTHONPATH=/home/airflow/airflow/:$PYTHONPATH。它的确切格式将取决于您使用的是什么(systemd与init脚本等)

重新添加sys路径对我有效

import sys
sys.path.insert(0,os.path.abspath(os.path.dirname(__file__)))

相关问题 更多 >