问题
如何给
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核心编程中称之为偏函数。