寻找一个简单的示例来演示 tornado.gen.coroutine
的使用的回调
参数。文档说:
Functions with [the
gen.coroutine
] decorator return aFuture
. Additionally, they may be called with acallback
keyword argument, which will be invoked with the future’s result when it resolves.
适应an example从文档的用户指南中,我认为我可以这样做:
from tornado import gen
@gen.coroutine
def divide(x, y):
return x / y
@gen.coroutine
def good_call():
yield divide(1, 2)
good_call(callback=print)
我希望打印 0.5
,但没有输出。
我发现了大量示例来展示已弃用的 gen.engine
装饰器,但 gen.coroutine 上似乎没有那么多。在 Python 3.5.1 和 Tornado 4.3 上运行。
最佳答案
您仍然需要启动 IOLoop。如果您在脚本末尾添加 tornado.ioloop.IOLoop.current().start()
,您将看到打印的输出(然后 IOLoop
永远运行.如果您希望它停止,您需要在打印后通过回调执行此操作)。
请注意,一般来说,可以(并且鼓励)仅使用协程和 yield 来编写 Tornado 应用程序,而不直接传递任何回调。
关于python - 在 Tornado 中使用 gen.coroutine 的回调参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068119/