gpt4 book ai didi

python - Twisted reactor 已停止,但程序并未结束?

转载 作者:太空狗 更新时间:2023-10-29 22:27:17 28 4
gpt4 key购买 nike

所以我正在编写一个与 Deluge 一起使用的小脚本。 Deluge 使用 Twisted,我真的不太了解它的工作原理。通常我会查找有关它的更多信息,但是开始使用 Twisted 会花费很长的时间并且超出了这个小项目的范围。所以我想我应该在这里问一下。

现在,我有了这段代码。我将尝试解释我需要帮助的特定部分

import base64

import processargs

from deluge.ui.client import client
from twisted.internet import reactor

from deluge.log import setupLogger
setupLogger()

options = processargs.readConfig(os.path.expanduser("~/.deluge-automator"))

d = client.connect(
host=options['host'],
port=int(options['port']),
username=options['username'],
password=options['password']
)

def start():
#other code

t = client.core.add_torrent_file(tfile,
base64.encodestring(data), None)

t.addCallback(on_torrent_added_success, tfile)
t.addErrback(on_torrent_added_fail)


def handle_stop_signal(SIGNAL, stack):
client.disconnect()
reactor.stop()


def on_torrent_added_success(result, tfile):
#other code
start()


def on_torrent_added_fail(result):
print "Add torrent failed!"
print "result: ", result


def on_connect_success(result):
#other code
start()


d.addCallback(on_connect_success)


def on_connect_fail(result):
print "Connection failed!"
print "result: ", result


d.addErrback(on_connect_fail)

signal.signal(signal.SIGTERM, handle_stop_signal)
signal.signal(signal.SIGINT, handle_stop_signal)

reactor.run()

当成功添加一个 torrent 时,它应该返回到 start(),它的确如此,但我认为它丢失了 react 器或其他东西。因为现在每当它收到 SIGTERM 或 SIGINT 时, react 堆就会关闭,但不会退出程序:

± % python2 main.py
Connection was successful!
result: 10
^C^CConnection failed!
result: [Failure instance: Traceback: <class 'twisted.internet.error.ReactorNotRunning'>: Can't stop reactor that isn't running.
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:551:_runCallbacks
/usr/lib/python2.7/site-packages/deluge/ui/client.py:412:__on_login
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:368:callback
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:464:_startRunCallbacks
--- <exception caught here> ---
/usr/lib/python2.7/site-packages/twisted/internet/defer.py:551:_runCallbacks
main.py:70:on_connect_success
main.py:32:start
main.py:49:handle_stop_signal
/usr/lib/python2.7/site-packages/twisted/internet/base.py:577:stop
]

所以 react 堆停止了,但它并没有退出程序。我必须键盘中断两次。一次停止 react 堆,第二次抛出错误。有没有特定的方法来设置这样的循环?

最佳答案

reactor 处理 sigint,sigterm 本身(可能有一个 reactor.run() 参数禁用它)。安装 reactor.addSystemEventTrigger('before', 'shutdown', client.disconnect) 代替。

参见 twisted: catch keyboardinterrupt and shutdown properly .

关于python - Twisted reactor 已停止,但程序并未结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13482550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com