我有一些异步功能,使用tornado gen.coroutine
,我通常将其用作基于龙卷风的Web应用程序的一部分。不过,我想从一个普通的旧Python脚本中调用其中的一些来执行一些管理任务。我该怎么做呢?在普通Python脚本中使用龙卷风异步代码
from tornado import gen
import some_internal_stuff
@gen.coroutine
def myfunc(x):
y = yield some_internal_stuff.another_async_func(x)
raise gen.Return(y)
if __name__ == "__main__":
# What do I put here to call myfunc(1) and get the async return value?
pass
更新:
更具体的例子:
from tornado import gen
@gen.coroutine
def another_async_func(x):
print "aaf"
raise gen.Return(x + 1)
@gen.coroutine
def myfunc(x):
print "myfunc"
y = yield another_async_func(x)
print "back"
raise gen.Return(y)
def callback(y):
print "Callback called with %d" % y
if __name__ == "__main__":
myfunc(1, callback=callback)
运行此输出:
myfunc
aaf
对不起,问这样一个明显的问题,但什么阻止你打电话some_internal_stuff.another_async_func(x)的直接并等待结果?你调用的函数是否依赖Tornado来防止这种情况发生? –
@rod:想法是'another_async_func'是另一个龙卷风'@异步'方法,通常在有龙卷风'IOLoop'的情况下运行。我可以运行'another_async_func'并将它传递给'callback',但没有龙卷风运行,'myfunc'中的产出之后的行永远不会运行,并且我传递的回调不会被调用。 – rakslice