Python 回调结束时如何正确停止扭曲反应器
我对Python还是很陌生,但我掌握了基本知识。我正试图编写一个脚本,使我能够与Flouge的API接口。现在我只是想把当前的下载队列取回来,但是反应器一直在运行。如果我将reactor.stop()放在flouge()onGetSessionState()的末尾,那么在flouge()onGetTorrentStatus()返回之前,reactor会停止 当onGetSessionState从onGetTorrentStatus获得所需的一切时,我对如何处理停止反应堆感到困惑Python 回调结束时如何正确停止扭曲反应器,python,twisted,Python,Twisted,我对Python还是很陌生,但我掌握了基本知识。我正试图编写一个脚本,使我能够与Flouge的API接口。现在我只是想把当前的下载队列取回来,但是反应器一直在运行。如果我将reactor.stop()放在flouge()onGetSessionState()的末尾,那么在flouge()onGetTorrentStatus()返回之前,reactor会停止 当onGetSessionState从onGetTorrentStatus获得所需的一切时,我对如何处理停止反应堆感到困惑 from del
from deluge.ui.client import client
from twisted.internet import reactor
class Deluge(object):
def __init__(self,*args):
for key, value in enumerate(args):
self.key = value
def getDownloadQueue(self):
self.connect("getQueue")
def connect(self,params):
deluge = client.connect()
deluge.addCallback(self.onConnect,params).addErrback(self.onConnectFail).addBoth(self.disconnect)
reactor.run()
def disconnect(self):
client.disconnect()
reactor.stop()
def onConnect(self,result,params):
def onGetTorrentStatus(torrentInfo):
print torrentInfo["name"] + " " + torrentInfo["label"]
def onGetSessionState(torrent_ids):
# This prints the torrent_ids just fine
print torrent_ids
# This only works if I keep the self.disconnect() below commented out
for id in torrent_ids:
client.core.get_torrent_status(id, ["name","label"]).addCallback(onGetTorrentStatus)
if params == "getQueue":
client.core.get_session_state().addCallback(onGetSessionState)
# self.disconnect()
def onConnectFail(self,result):
print "Error: %s" % result
reactor.stop()
deluge = Deluge()
deluge.getDownloadQueue()
您遇到的具体问题是,
onGetTorrentStatus
被添加为对多个延迟的回调(因为它被添加到循环中的torrent\u id
)
一旦第一个get\u torrent\u status
Deferred得到结果,就会调用onGetTorrentStatus
。如果onGetTorrentStatus
停止反应堆,则其他状态调用都没有机会完成
您希望等待所有的get\u torrent\u status
延迟在停止之前获得结果
twisted.internet.defer.gatherResults
应该可以帮助您解决这个问题
您可能还想看看
twisted.internet.task.react
,它将替换您对reactor.run
和reactor.stop
(您仍然需要收集结果
,或者react
将不知道调用reactor.stop
的正确时间).您可以通过调用client.core.get\u torrents\u status
避免多次延迟问题并简化脚本,它将返回会话中的所有当前torrent id和指定的状态键。我仍然无法使此工作。我相信你的答案是正确的,我只需要对Twisted做更多的研究。谢谢