如何在回拨结束后正确停止扭曲电抗器 [英] How to properly stop Twisted reactor when callback is finished

查看:14
本文介绍了如何在回拨结束后正确停止扭曲电抗器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是个新手,但我已经掌握了一些基础知识。我正在尝试编写一个脚本,将允许我与洪水的API接口。现在我只是想找回当前的下载队列,但反应堆仍在运行。如果我在fluge().onGetSessionState()的末尾放入reactor.top(),那么在fluge().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()

推荐答案

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

一旦第一个get_torrent_status得到结果,onGetTorrentStatus就会被调用。如果onGetTorrentStatus停止反应器,则其他任何状态调用都无法完成。

您要等待所有get_torrent_status延期得到结果后再停止。

twisted.internet.defer.gatherResults应该对您有帮助。

您可能还想看看twisted.internet.task.react,它将替换您对reactor.runreactor.stop的调用(但您仍然需要gatherResults,否则react也不知道调用reactor.stop的正确时间)。

这篇关于如何在回拨结束后正确停止扭曲电抗器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆