Python 自定义操作器

Python 自定义操作器,python,airflow,Python,Airflow,我正在尝试自定义该操作符,但它不起作用。到目前为止我已经试过了 my_operators.py 运算符_example.py 气流GUI显示错误消息断开DAG:[/usr/local/aiffort/dags/operator\u example.py]参数['bash\u command']是必需的 这次尝试有什么问题?我知道我可以从复制或模仿BashOperator的实现,但这不是我想要的。注意我们如何将bash_命令传递给我们从中继承的类 from airflow.utils.decora

我正在尝试自定义该操作符,但它不起作用。到目前为止我已经试过了

my_operators.py

运算符_example.py

气流GUI显示错误消息断开DAG:[/usr/local/aiffort/dags/operator\u example.py]参数['bash\u command']是必需的


这次尝试有什么问题?我知道我可以从复制或模仿BashOperator的实现,但这不是我想要的。注意我们如何将
bash_命令
传递给我们从中继承的类

from airflow.utils.decorators import apply_defaults
from airflow.operators.bash_operator import BashOperator

class MyCopyOperator(BashOperator):

    template_fields = ('bash_command', 'source_file', 'source_dir', 'target_file', 'target_dir')


    @apply_defaults
    def __init__(
            self,
            source_file, 
            source_dir, 
            target_file, 
            target_dir,
            *args, **kwargs):

        super(MyCopyOperator, self).__init__(bash_command="cp " + " " + source_dir + "/" + source_file + " " + target_dir + "/" + target_file, *args, **kwargs)
        self.source_file = source_file
        self.source_dir = source_dir
        self.target_file = target_file
        self.target_dir = target_dir     

示例任务:

MyCopyOperator(
    task_id='print_date12',
    source_file='test.txt',
    source_dir='/Users/kaxilnaik/Desktop',
    target_file="test1.txt",
    target_dir="/Users/kaxilnaik/Desktop/abc",
    dag=dag)

非常感谢,它可以工作,但是当运行DAG时,我会收到错误消息cp:missing file operator,而具有相同bash_命令的bash操作符的工作方式类似于charm
bash_test=bash operator(task_id='bash_test',bash_command='cp/usr/local/aiffort/test_file.txt/usr/local/aiffort/test_file.copied.txt',DAG=DAG,)
我已经更新了答案,请使用并检查。我还添加了一个对我有效的示例任务。现在它成功了。谢谢。我使用了MyCopyOperator(task#id='print#date12',bash#u command=“#。我再次编辑了答案。使用新代码时,您无需输入
bash#u command=“##########”
:)如果任何参数包含引用字符、通配符、空格等,这将以令人讨厌的方式失败。一个更好但更复杂的解决方案将避免为这个简单操作调用shell,只需使用
subprocess.run()
直接调用
cp
。也许你也会看到
from airflow.utils.decorators import apply_defaults
from airflow.operators.bash_operator import BashOperator

class MyCopyOperator(BashOperator):

    template_fields = ('bash_command', 'source_file', 'source_dir', 'target_file', 'target_dir')


    @apply_defaults
    def __init__(
            self,
            source_file, 
            source_dir, 
            target_file, 
            target_dir,
            *args, **kwargs):

        super(MyCopyOperator, self).__init__(bash_command="cp " + " " + source_dir + "/" + source_file + " " + target_dir + "/" + target_file, *args, **kwargs)
        self.source_file = source_file
        self.source_dir = source_dir
        self.target_file = target_file
        self.target_dir = target_dir     

MyCopyOperator(
    task_id='print_date12',
    source_file='test.txt',
    source_dir='/Users/kaxilnaik/Desktop',
    target_file="test1.txt",
    target_dir="/Users/kaxilnaik/Desktop/abc",
    dag=dag)