Airflow中导入DAG时出现ImportError的技术问题求助
Let's break down what's causing this error and how to fix it quickly:
The Root Cause
Your script is named airflow.py — this is conflicting with the official Airflow library! When Python runs from airflow import DAG, it looks for modules in the current directory first. Instead of loading the actual Airflow library installed on your system, it's trying to import from your own airflow.py file, creating a circular import loop (which is why the traceback shows it's stuck on your local file).
Step-by-Step Fix
Rename your DAG file
Change the filename fromairflow.pyto something that doesn't clash with the library name, likedaily_data_pipeline.pyormy_s3_to_postgres_dag.py.Clean up cached files
If there's anairflow.pycfile (Python's compiled bytecode) in your directory, delete it. This file might still reference the old naming and cause errors even after you rename the script.Update operator imports (for Airflow 2.x+)
Looking at your code, you're importingS3KeySensorfromairflow.operators— this path is outdated for Airflow 2.x. Update that import to:from airflow.providers.amazon.aws.sensors.s3_key import S3KeySensor(You'll need to make sure the
apache-airflow-providers-amazonpackage is installed if you haven't already.)
Corrected Code Snippet
from airflow import DAG from airflow.operators.bash import BashOperator from airflow.providers.amazon.aws.sensors.s3_key import S3KeySensor from datetime import datetime, timedelta, date import psycopg2 yesterday = date.today() - timedelta(1) yesterdayDate = yesterday.strftime('%Y-%m-%d') # Add your DAG definition and task logic here...
Quick Additional Checks
- Make sure your Airflow environment is properly configured (correct
AIRFLOW_HOMEsetting, DAGs placed in the designateddagsdirectory). - Confirm you're running the script in the virtual environment where Airflow is installed.
内容的提问来源于stack exchange,提问作者Vivek Mehendiratta

