如何将参数传递给python tornado IOLoop run_sync(main)函数
我正在使用python tornado运行非块函数,我应该如何将参数传递给主函数如何将参数传递给python tornado IOLoop run_sync(main)函数,python,Python,我正在使用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_u
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)
方法
IOLoop.run_sync()
a接受对函数的引用并尝试调用它
所以,如果您想用指定的参数运行非阻塞函数,您应该用另一个函数包装它
您可以使用附加功能执行此操作,以下两个示例都是正确的:
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))
您可以使用
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)