关于 Twisted的inlineCallbacks
简单理解
正如文档中所说inlineCallbacks
可以帮助你使用看起来像有规整的顺序的函数代码去写回调函数Deferred
.
如下小例子:
import sys
import time
from twisted.python import log
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
log.startLogging(sys.stdout)
class Section(object):
def __init__(self):
self.sentence = "I'm now in Methods: "
@inlineCallbacks
def run(self):
sections = ['audio', 'upload']
for stage, name in enumerate(sections, 1):
method = 'section_%s' % name
result = yield getattr(self, method)()
print(result)
print('Now the stage: {}'.format(stage))
@inlineCallbacks
def section_audio(self):
time.sleep(3)
r = yield self.sentence + 'audio...'
returnValue(r)
@inlineCallbacks
def section_upload(self):
time.sleep(2)
r = yield self.sentence + 'upload...'
returnValue(r)
if __name__ == '__main__':
s = Section()
s.run()
reactor.run()
如上边小例子,使用inlineCallbacks
可以将twisted的任务,按照我们所写的代码顺序运行。而在使用inlineCallbacks
时,需要函数返回一个生成器,所以我们使用yield
。因为inlineCallbacks
是把生成器变成一系列的callbacks进行执行。
网友评论