首页 > 解决方案 > 运行 bashoperator 时气流重置环境变量

问题描述

在我的一项气流任务中,我遇到了环境变量问题。

[2019-08-19 04:51:04,603] {{bash_operator.py:127}} INFO -   File "/home/ubuntu/.pyenv/versions/3.6.7/lib/python3.6/os.py", line 669, in __getitem__
[2019-08-19 04:51:04,603] {{bash_operator.py:127}} INFO -     raise KeyError(key) from None
[2019-08-19 04:51:04,603] {{bash_operator.py:127}} INFO - KeyError: 'HOME'
[2019-08-19 04:51:04,639] {{bash_operator.py:131}} INFO - Command exited with return code 1

我的任务如下:

task_name = BashOperator(
    task_id='task_name',
    bash_command="cd path/to/manage.py && export LC_ALL=C.UTF-8 && export LANG=C.UTF-8 "
    f'&& {Variable.get("python_virtualenv_path")}virtual-env-name/bin/python manage.py command_name',
    retries=1,
    pool='LightAndFast',
    dag=dag
)

对这个问题有任何想法吗?

标签: pythonairflow

解决方案


确实,气流会重置环境变量,在使用时BashOperator,至少我遇到了这个问题。在操作员的文档中,可在以下网址获得: https ://airflow.apache.org/docs/stable/_modules/airflow/operators/bash_operator.html ,我找到了为 bash 命令显式设置环境的方法,即

bash_task = BashOperator(
        task_id="bash_task",
        bash_command='echo "here is the message: \'$message\'"',
        env={'message': '{{ dag_run.conf["message"] if dag_run else "" }}'},
    )

因此,我将 Bash 命令的环境显式设置为:

env = os.environ.copy(),

确保import osdag文件中早先。它为我解决了这个问题。


推荐阅读