繁体   English   中英

在常规python脚本中使用tornado异步代码

[英]Use tornado async code in a regular python script

我有一些使用tornado gen.coroutine异步函数,我通常将其用作基于龙卷风的Web应用程序的一部分。 但是,我想从一个普通的旧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

有一个内置的方法run_syncIOLoop运行一个单一的呼叫,然后停止循环,所以它是非常容易的,只是添加事件循环,只要你有在PYTHONPATH龙卷风纯python脚本。

通过具体的例子:

from tornado import gen, ioloop

@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)

@gen.coroutine
def main():
    y = yield myfunc(1)
    print "Callback called with %d" % y

if __name__ == "__main__":
    ioloop.IOLoop.instance().run_sync(main)

这输出:

myfunc
aaf
back
Callback called with 2

请注意, run_sync不能很好地嵌套; 如果你打电话run_sync在被调用的函数run_sync在同一IOLoop内调用完成将停止IOLoop并没有进一步的yield内部调用返回后秒。

这是使用线程的另一种可能性,它可以根据问题的复杂性和您的需求而工作:

if __name__ == "__main__":
    import threading, time
    # The tornado IO loop doesn't need to be started in the main thread
    # so let's start it in another thread:
    t = threading.Thread(target=IOLoop.instance().start)
    t.daemon = True
    t.start()

    myfunc(1, callback=callback)
    # now the main loop needs wait; you can do that by polling a value, sleeping,
    # or waiting on a lock. I've chosen to sleep here, but a lock is probably more
    # appropriate; and, once computation is done, release the lock.
    time.sleep(2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM