我正在使用 python tornado 运行非 block 函数,我应该如何将参数传递给主函数?
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()
接受对函数的引用并尝试调用它。
所以,如果你想运行带有指定参数的非阻塞函数,你应该用另一个函数包装它。
你可以使用额外的函数来做到这一点,下面的两个例子都是正确的:
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))
关于python - 如何将参数传递给 python tornado IOLoop run_sync(main) 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30782113/