如何从脚本/模块main启动芹菜工人?

2024-04-24 20:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'])

但这抱怨说,-A没有被识别。

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


Tags: 模块nameprojectapp应用程序消息定义main
3条回答

我想你只是没有把args包装起来,这样芹菜就能读出来,比如:

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

使用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)

基于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)

相关问题 更多 >