如何从脚本/模块__main__启动Celery工作者?

时间:2014-04-30 13:13:21

标签: python celery celeryd

我在模块中定义了一个Celery应用,现在我想从__main__中的同一个模块启动该工作,即通过{{1}运行模块而不是命令行中的python -m。我试过这个:

celery

但是现在Celery认为我没有参数运行工人:

app = Celery('project', include=['project.tasks'])

# do all kind of project-specific configuration
# that should occur whenever this module is imported

if __name__ == '__main__':
    # log stuff about the configuration
    app.start(['worker', '-A', 'project.tasks'])

使用消息是您从Usage: worker <command> [options] Show help screen and exit. Options: -A APP, --app=APP app instance to use (e.g. module.attr_name) [snip] 获得的消息,就好像它没有获得命令一样。我也试过了

celery --help

但抱怨app.worker_main(['-A', 'project.tasks']) 无法识别。

那我该怎么做?或者,如何将回调传递给worker以使其记录有关其配置的信息?

5 个答案:

答案 0 :(得分:17)

使用app.worker_main方法(v3.1.12):

± cat start_celery.py
#!/usr/bin/python

from myapp import app


if __name__ == "__main__":
    argv = [
        'worker',
        '--loglevel=DEBUG',
    ]
    app.worker_main(argv)

答案 1 :(得分:10)

基于code from Django-Celery module你可以尝试这样的事情:

from __future__ import absolute_import, unicode_literals

from celery import current_app
from celery.bin import worker


if __name__ == '__main__':
    app = current_app._get_current_object()

    worker = worker.worker(app=app)

    options = {
        'broker': 'amqp://guest:guest@localhost:5672//',
        'loglevel': 'INFO',
        'traceback': True,
    }

    worker.run(**options)

答案 2 :(得分:3)

我认为你只是缺少包裹args所以芹菜可以读取它们,如:

queue = Celery('blah', include=['blah'])
queue.start(argv=['celery', 'worker', '-l', 'info'])

答案 3 :(得分:1)

Celery 5起,一切已更改

worker_main的结果如下:

AttributeError: 'Celery' object has no attribute 'worker_main'

对于芹菜5,请执行以下操作:

app = celery.Celery(
    'project',
    include=['project.tasks']
)

if __name__ == '__main__':
    worker = app.Worker(
        include=['project.tasks']
    )
    worker.start()

有关详细信息,请参见此处celery.apps.workercelery.worker.WorkController.setup_defaults(希望将来会得到更好的记录)。

答案 4 :(得分:1)

worker_main被放回芹菜5.0.3中: https://github.com/celery/celery/pull/6481

这对我而言适用于5.0.4:

self.app.worker_main(argv = ['worker', '--loglevel=info', '--concurrency={}'.format(os.environ['CELERY_CONCURRENCY']), '--without-gossip'])