【问题标题】:How to properly stop Twisted reactor when callback is finished回调完成后如何正确停止 Twisted reactor
【发布时间】:2014-01-25 04:11:05
【问题描述】:

我对 Python 还是很陌生,但我掌握了基础知识。我正在尝试编写一个允许我与 Deluge 的 API 交互的脚本。现在我只是想找回当前的下载队列,但反应堆一直在运行。如果我将 reactor.stop() 放在 Deluge().onGetSessionState() 的末尾,那么反应器会在 Deluge().onGetTorrentStatus() 回来之前停止。

当 onGetSessionState 从 onGetTorrentStatus 获得所需的一切时,我对如何处理停止反应器感到困惑。

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()

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    您遇到的具体问题是 onGetTorrentStatus 被添加为多个 Deferred 的回调(因为它被添加到 torrent_ids 的循环内)。

    只要第一个get_torrent_status Deferred 得到结果,就会调用onGetTorrentStatus。如果onGetTorrentStatus 停止反应器,则其他状态调用都没有机会完成。

    您想等待 所有 get_torrent_status Deferreds 在停止之前获得结果。

    twisted.internet.defer.gatherResults 应该可以帮到你。

    您可能还想查看twisted.internet.task.react,它将替换您对bothreactor.runreactor.stop 的调用(尽管您仍然需要gatherResults,或者react 不会知道拨打reactor.stop的正确时间。

    【讨论】:

    • 我仍然无法让它工作。我相信你的答案是正确的,我只需要对 Twisted 做更多的研究。谢谢!
    【解决方案2】:

    您可以通过调用client.core.get_torrents_status 来避免多个延迟问题并简化您的脚本,它将返回会话中的所有当前种子 ID 和指定的状态键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      相关资源
      最近更新 更多