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

标签 python

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

相关文章:

python - 示例 urllib3 和 python 中的线程

python - 如何修复 'TypeError: unlink() missing 1 required positional argument:\' 值\'\n' '

python - 我怎样才能在sql查询中转义这个字符串?

python - Python 中 numpy.random 和 random.random 的性能差异

python - 无法从 Cloud9 python 应用程序连接到 MySQL 数据库(托管在 arvixe 中)

python - 5 的组合的最大可能值

python - 自动运行 python 脚本而无需重新加载依赖项

python - 将python列表转换为float

python - 从 Python 中的类方法返回多个值的最有效方法是什么?

python - 接收错误: Reverse for with arguments '()' and keyword arguments not found