如何向Python Tornado的IOLoop run_sync(main)函数传递参数?

5
我正在使用 Python Tornado 运行非阻塞函数,我应该如何传递参数到主函数?
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个回答

8

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

因此,如果您想要运行具有指定参数的非阻塞函数,则应将其包装在另一个函数中。

您可以使用附加的函数来完成这个过程,下面这两个示例都是正确的:

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

ioloop.IOLoop.current().run_sync(run_with_args(main, index))
< p >使用lambda的简短方式:

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

1
你可以使用 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接