当命令执行失败时,Celery任务会成功

时间:2014-06-09 21:46:46

标签: python flask rabbitmq task celery

我有一个看起来像这样的tasks.py文件:

from celery import Celery
import subprocess
from flask import flash

app = Celery('tasks', backend='amqp', broker='amqp://guest@localhost//')

@app.task(track_started=True)
def move_files(upRepo, filedir):
    subprocess.call(['aptly', 'repo', 'add', upRepo, filedir])

@app.task(track_started=True)
def make_snapshot(existRepoName, snapName):
    subprocess.call(['aptly', 'snapshot', 'create', snapName, 'from', 'repo', existRepoName])

任务很顺利,当subprocess.call命令成功完成所有工作时,就在subprocess.call失败时,任务仍然在技术上完成,因此Celery将此报告为& #39;成功'

我一直在the docs查看after_return,但我不确定这是不是我想要的,我也不知道如何实施该...

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试subprocess.check_call - 如果出现问题,它会抛出异常。

测试用例:

import subprocess

subprocess.check_call('false')

输出

Traceback (most recent call last):
  File "zcheck.py", line 3, in <module>
    subprocess.check_call('false')
  File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'false' returned non-zero exit status 1

对于原始代码,这将成为:

tasks.py

from celery import Celery
import subprocess
from flask import flash

app = Celery('tasks', backend='amqp', broker='amqp://guest@localhost//')

@app.task(track_started=True)
def move_files(upRepo, filedir):
    subprocess.check_call(['aptly', 'repo', 'add', upRepo, filedir])

@app.task(track_started=True)
def make_snapshot(existRepoName, snapName):
    subprocess.check_call(['aptly', 'snapshot', 'create', snapName, 'from', 'repo', existRepoName])