所以我正在编写一个与Deluge一起使用的小脚本。 Deluge使用Twisted,我真的没有牢牢掌握它是如何工作的。通常情况下,我只是查找更多信息,但是开始使用Twisted会花费 long 时间,这超出了这个小项目的范围。所以我想我会问这里。
现在,我有这个代码。我将尝试解释我需要帮助的具体部分
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(),它确实如此,但我认为它会丢失反应堆或其他东西。因为现在只要收到SIGTERM或SIGINT,反应堆就会关闭,但不会退出程序:
± % 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
]
所以反应堆停止了,但它没有退出程序。我要两次键盘中断。一旦停止反应堆,第二次抛出错误。是否有某种方法来设置这样的循环?
答案 0 :(得分:8)
reactor处理sigint,sigterm本身(可能有reactor.run()
的参数禁用它)。改为安装reactor.addSystemEventTrigger('before', 'shutdown', client.disconnect)
。