gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:49:20 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com