如何将params传递给python tornado IOLoop run_sync(main)函数

时间:2015-06-11 13:25:38

标签: python

我使用python tornado来运行非阻塞功能,我应该如何将params传递给main函数?

from __future__ import print_function
from tornado import ioloop, gen
import tornado_mysql
import time

@gen.coroutine
def main(index):
    conn = yield tornado_mysql.connect(host=db_host, port=3306, user=db_user, passwd=db_psw, db=db_db)
    cur = conn.cursor()
    sql = 'INSERT INTO `ctp_db`.`if1506` (`bid`) VALUES (%s)'
    yield cur.execute(sql, (index))
    conn.commit()
    cur.close()
    conn.close()

ioloop.IOLoop.current().run_sync(main)

2 个答案:

答案 0 :(得分:6)

方法IOLoop.run_sync()接受对函数的引用并尝试调用它。

因此,如果你想用指定的参数运行非阻塞函数,你应该用另一个函数包装它。

您可以使用附加功能执行此操作,以下两个示例均正确无误:

def run_with_args(func, *args):
    return func(*args)

ioloop.IOLoop.current().run_sync(run_with_args(main, index))

lambda的缩短方式:

ioloop.IOLoop.current().run_sync(lambda: main(index))

答案 1 :(得分:0)

你可以使用functools.partial 例如:

from tornado import gen
from tornado.ioloop import IOLoop

@gen.coroutine
def func():
    print('this is the %(name)s'%{'name': func.__name__})
    yield gen.sleep(6.0)
    print('%(num)d'%{'num': 10})


@gen.coroutine
def foo():
    print('this is the %(name)s'%{'name': foo.__name__})
    yield gen.sleep(1.5)
    print('%(num)d'%{'num': 5})


@gen.coroutine
def call():
    yield gen.sleep(0)
    print('this is the callback')


@gen.coroutine
def main(ioloop):
    ioloop.call_later(5, call)
    yield [func(), foo()]


if __name__ == '__main__':
    from functools import partial
    ioloop = IOLoop.current()
    main = partial(main, ioloop=ioloop)
    ioloop.run_sync(main)