python - 在 Tornado 中使用 gen.coroutine 的回调参数

标签 python python-3.x asynchronous tornado

寻找一个简单的示例来演示 tornado.gen.coroutine 的使用的回调参数。文档说:

Functions with [the gen.coroutine] decorator return a Future. Additionally, they may be called with a callback 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/

相关文章:

带有 sys.argv[] 的 Python 3.x 调用函数

python - pandas dataframe-替换行值

python-3.x - Astropy:确定一个点(RA,DEC)是否在给定该区域角坐标的方形区域内

python - 我无法在 python 中使用 matplotlib 在 close() 之后调用 show()

Python:根据多个条件聚合和平均行

python - Django名称错误: name 'Character' is not defined

python - 为什么我们使用 `wraps` 而不是 `update_wrapper` 作为装饰器?

node.js - 我正在导入一个异步函数并尝试使用它

javascript - 异步函数完成后如何开始执行函数?在这种情况下, promise 不起作用

c++ - 异步 ReadDirectoryChangesW()?