各位, 我完全糊涂了,所以有可能我问的问题都不对,但这里有:
我有一个使用内联回调的扭曲应用程序。现在我需要定义一个迭代器,它意味着一个生成器被返回给调用者。但是,迭代器不能被内联回调修饰,对吗?如果不是,那我该如何编写这样的代码。
只需澄清一下:目标是进程循环需要每5秒调用一次,它只能处理其中的一块,比如10秒,然后它必须放手。但是,要知道10块(存储在cached中,这是dict的dict),它需要调用一个返回deferred的函数。
@inlineCallbacks ### can\'t have inlineCallbacks here, right?
def cacheiter(cached):
for cachename,cachevalue in cached.items():
result = yield (call func here which returns deferred)
if result is True:
for k,v in cachedvalue.items():
yield cachename, k, v
@inlineCallbacks
def process_chunk(myiter, num):
try:
for i in xrange(num):
nextval = myiter.next()
yield some_processing(nextval)
returnValue(False)
except StopIteration:
returnValue(True)
@inlineCallbacks
def process_loop(cached):
myiter = cacheiter(cached)
result = yield process_chunk(myiter, 10)
if not result:
print 'More left'
reactor.callLater(5, process_loop, cached)
else:
print 'All done'
我想你是想这么做:
当genexp无法表达您试图返回的内容时,可以编写一个闭包:
尝试将迭代器编写为^{} 。
你说得对,你不能用
cacheiter
来表达你想表达的东西。装饰器不允许有返回迭代器的函数。如果用它修饰函数,则结果是始终返回Deferred
的函数。这就是它的用途。造成这种困难的部分原因是迭代器不能很好地处理异步代码。如果生成迭代器的元素涉及延迟,那么迭代器中的元素将首先延迟。
你可以这样解释:
这可以工作,但看起来特别奇怪。由于生成器只能向其调用者屈服(例如,不能向其调用者的调用者屈服),因此
some_jobs
迭代器对此无能为力;只有在process_work
内的词汇代码才能产生延迟到inlineCallbacks
提供的蹦床等待的延迟。如果您不介意这种模式,那么我们可以想象您的代码正在被编写如下:
不过,您可以采取的另一种方法是使用
twisted.internet.task.cooperate
。cooperate
接受一个迭代器并使用它,假设使用它潜在的成本很高,并在多个reactor迭代中分割作业。从上面得到cacheiter
的定义:相关问题 更多 >
编程相关推荐