当前位置: 首页 > 工具软件 > Python_Sync > 使用案例 >

tornado学习笔记(一):如何给ioloop.run_sync()中调用的函数传入参数

杭英杰
2023-12-01

问题
如何给tornado.ioloop.IOLoop中的run_sync方法中调用的函数添加参数

解决方案
使用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)

总结
利用functools.partial就可以把原本需要带参数调用的函数变成不需要带参数就可以调用,在python核心编程中称之为偏函数。

 类似资料: