Python 如何从脚本/模块 __main__ 启动 Celery Worker?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23389104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to start a Celery worker from a script/module __main__?
提问by Fred Foo
I've define a Celery
app in a module, and now I want to start the worker from the same module in its __main__
, i.e. by running the module with python -m
instead of celery
from the command line. I tried this:
我已经Celery
在一个模块中定义了一个应用程序,现在我想从它的同一个模块启动工作程序__main__
,即通过运行模块python -m
而不是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'])
but now Celery thinks I'm running the worker without arguments:
但现在 Celery 认为我在不加参数地运行工人:
Usage: worker <command> [options]
Show help screen and exit.
Options:
-A APP, --app=APP app instance to use (e.g. module.attr_name)
[snip]
The usage message is the one you get from celery --help
, as if it didn't get a command. I've also tried
使用消息是您从 获得的消息celery --help
,就好像它没有获得命令一样。我也试过
app.worker_main(['-A', 'project.tasks'])
but that complains about the -A
not being recognized.
但这抱怨-A
不被认可。
So how do I do this? Or alternatively, how do I pass a callback to the worker to have it log information about its configuration?
那么我该怎么做呢?或者,我如何将回调传递给工作人员以使其记录有关其配置的信息?
采纳答案by daniula
Based on code from Django-Celery moduleyou could try something like this:
基于来自 Django-Celery 模块的代码,你可以尝试这样的事情:
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)
回答by okocian
using app.worker_main method (v3.1.12):
使用 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)
回答by nurieta
I think you are just missing wrapping the args so celery can read them, like:
我认为您只是缺少包装 args 以便 celery 可以读取它们,例如:
queue = Celery('blah', include=['blah'])
queue.start(argv=['celery', 'worker', '-l', 'info'])