我有一个类似的问题,因为这不能让python从另一个文件夹导入解决方案无法解决我的问题。
我正在使用气流库。lib更新了其中一个操作程序,由于此时无法升级我的airflow版本,我想手动下载操作程序.py文件并在我的代码手册中使用它。
airflow
-dags
--mydag.py
-AddedOperators
--sagemaker_tuning_operator.py
--__init__.py (empty file)
sagemaker_tuning_operator.py是以下文件:https://github.com/apache/airflow/blob/master/airflow/contrib/operators/sagemaker_tuning_operator.py
它包含类SageMakerTuningOperator。
在我的mydag.py中,我是:
from AddedOperators.sagemaker_tuning_operator import SageMakerTuningOperator
号
当气流试图分析mydag.py时,我得到:
No module named AddedOperators.sagemaker_tuning_operator
号
检查项目目录是否在系统路径中。您可以按如下方式检查:
import sys
print(sys.path)
Note that when running a Python script, sys.path doesn’t care what
your current"working directory" is. It only cares about the path to
the script. For example, if my shell is currently at the Airflow/
folder and I run python ./dags/mydag.py, then sys.path includes
Airflow/dags/ but NOT Airflow/
号
如果项目目录不在sys路径中,可以执行以下操作:
动态地包括它。
import sys
sys.path.insert(0, 'path/to/your/')
# import your module now
号
将项目根文件夹中所有必需的模块导入到app.py之类的文件中,然后从此处调用。
它不在sys.path中。我做了:sys.path.insert(0,/home/ubuntu/airflow')仍然不起作用。相同的错误
动态添加路径对我来说很好。你能展示一下你做了什么吗?