尝试实现扭曲的deferredlist时的奇怪行为 [英] Strange behaviour when trying to implement twisted deferredlist
问题描述
我刚开始尝试构建简单的POC,但是我不断遇到以下错误.
I'm new to twisted and trying to build a simple POC, however I keep getting the following error.
running
[]
running
[]
running
[]
running
[]
running
[]
Traceback (most recent call last):
File "./poc.py", line 23, in <module>
dl = defer.DeferredList([tasks])
File "/usr/local/lib/python2.7/site-packages/twisted/internet/defer.py", line 820, in __init__
deferred.addCallbacks(self._cbDeferred, self._cbDeferred,
AttributeError: 'list' object has no attribute 'addCallbacks'
我一直在阅读相关的扭曲文档和指南,但似乎无法弄清我做错了什么.有人知道导致此异常的原因吗?
I have been reading through the relevant twisted documentation and guides and can't seem to work out what I'm doing wrong. Does anybody know what is causing this exception?
#!/usr/bin/env python
from twisted.internet import defer
def task_to_run(data):
print 'running'
print data
def finished(res):
print 'finished', res
tasks = []
for x in range(0,5):
d = defer.Deferred()
d.addCallback(task_to_run)
tasks.append(d)
dl = defer.DeferredList([tasks])
dl.addCallback(finished)
推荐答案
假设 task_to_run
确实是异步运行的,那么@Elisha就是在指出您的问题(您的示例代码列出了列表,它不应该).因此,可运行的代码如下:
Assuming that task_to_run
really is something that is running async, then @Elisha was pointing you at the issue (your example code lists the list and it shouldn't). So runnable code looks like:
#!/usr/bin/env python
from twisted.internet import defer
def task_to_run(data):
print 'running'
print data
def finished(res):
print 'finished', res
tasks = []
for x in range(0,5):
d = defer.Deferred()
d.addCallback(task_to_run)
d.callback("blah - " + str(x)) # Fire them as I make them
tasks.append(d)
dl = defer.DeferredList(tasks)
dl.addCallback(finished)
输出为:
% ./deferredList.py
running
blah - 0
running
blah - 1
running
blah - 2
running
blah - 3
running
blah - 4
finished [(True, None), (True, None), (True, None), (True, None), (True, None)]
关于DeferredLists的非常不错的文档位于:延迟参考
BTW very nice docs on DeferredLists are at: Deferred Reference
但是,如果任务实际上并未异步运行,那么您真的可以只设置一个延迟队列:
But if the tasks aren't actually running async then you really could just make one defer queue:
#!/usr/bin/env python
from twisted.internet import defer
def task_to_run(data):
print 'running'
print data
return data
def finished(res):
print 'finished', res
d = defer.Deferred()
for x in range(0,5):
d.addCallback(task_to_run)
d.addCallback(finished)
d.callback("blah") # Fire the deferred
运行方式:
% ./deferred.py
running
blah
running
blah
running
blah
running
blah
running
blah
finished blah
这篇关于尝试实现扭曲的deferredlist时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!