手动返回芹菜任务的错误结果和状态失败?

Ala*_*lan 3 python celery

我已经创建了芹菜任务来运行一些通过nodejs用javascript编写的各种工作.该任务基本上是一个subprocess.popen调用nodejs 的任务.

退出时nodejs作业将返回非零状态,以及写入stderr的错误信息.

当发生这种情况时,我想采取stderr,并将其作为"结果"返回给芹菜,以及FAILURE状态,这样我的工作监视器可以反映作业失败.

我怎样才能做到这一点?

这是我的任务

@app.task
def badcommand():
    try:
       output = subprocess.check_output('ls foobar',stderr=subprocess.STDOUT,shell=True)
       return output
    except subprocess.CalledProcessError as er:
       #What do I do here to return er.output, and set the status to fail?
Run Code Online (Sandbox Code Playgroud)

如果我没有捕获子进程异常,则Job正确失败,但结果为空,我得到一个回溯堆栈跟踪.

如果我抓住异常,并返回er.output完成的工作成功.

olo*_*fom 5

您可以使用具有指定失败时要执行的操作的功能的基础。

class YourBase(Task):
    def on_success(self, retval, task_id, args, kwargs):
        print "Failure"

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print "Success"

@app.task(base=YourBase)
def badcommand():
   output = subprocess.check_output('ls foobar', stderr=subprocess.STDOUT, shell=True)
   return output
Run Code Online (Sandbox Code Playgroud)

这些是您的基类可以使用的处理程序:http://celery.readthedocs.org/en/latest/userguide/tasks.html#handlers

  • 为什么投反对票?应该可以解决问题,并且符合celery的准则。 (2认同)

Bal*_*rol 5

您可以使用celery.app.task.Task.update_state方法更新当前任务状态.

@app.task(bind=True)
def badcommand(self):
    try:
       output = subprocess.check_output('ls foobar',stderr=subprocess.STDOUT,shell=True)
       return output
    except subprocess.CalledProcessError as er:
        self.update_state(state='FAILURE', meta={'exc': er})
Run Code Online (Sandbox Code Playgroud)

请注意,装饰器的bind参数app.task是在Celery 3.1中引入的.如果您仍在使用旧版本,我认为您可以通过update_state这种方式调用任务方法:

@app.task
def badcommand():
    ...
    except subprocess.CalledProcessError as er:
        badcommand.update_state(state='FAILURE', meta={'exc': er})    
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。除非您抛出异常或以某种方式失败,否则芹菜似乎将状态更新为“成功”,由芹菜确定,例如,请参阅 /sf/answers/2320048181/ (2认同)