天天看點

tornado學習筆記(一):如何給ioloop.run_sync()中調用的函數傳入參數

問題

如何給

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()
    print('%(num)d'%{'num': })


@gen.coroutine
def foo():
    print('this is the %(name)s'%{'name': foo.__name__})
    yield gen.sleep()
    print('%(num)d'%{'num': })


@gen.coroutine
def call():
    yield gen.sleep()
    print('this is the callback')


@gen.coroutine
def main(ioloop):
    ioloop.call_later(, 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核心程式設計中稱之為偏函數。

繼續閱讀