首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何优雅地退出由twistd启动的应用程序?

如何优雅地退出由twistd启动的应用程序?
EN

Stack Overflow用户
提问于 2011-03-17 19:23:34
回答 3查看 8.4K关注 0票数 12

我有一个jabber客户端正在读取它的stdin并发布PubSub消息。如果我在stdin上看到EOF,我想终止客户。

我首先尝试了sys.exit(),但是这会导致异常,并且客户机不会退出。然后我做了一些搜索,发现我应该打电话给reactor.stop(),但我无法完成这项工作。我的客户端中的以下代码:

代码语言:javascript
复制
from twisted.internet import reactor
reactor.stop()

exceptions.AttributeError: 'module' object has no attribute 'stop'的结果

我需要做什么才能使twistd关闭我的应用程序并退出?

编辑2

最初的问题是由于一些符号链接扰乱了模块导入。在解决了这个问题之后,我得到了一个新的例外:

代码语言:javascript
复制
twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.

异常之后,twistd关闭。我认为这可能是由于调用MyClient.loop in MyClient.connectionInitialized造成的。也许我需要把电话推迟到以后再打?

编辑

这是我客户的.tac文件

代码语言:javascript
复制
import sys

from twisted.application import service
from twisted.words.protocols.jabber.jid import JID

from myApp.clients import MyClient

clientJID = JID('client@example.com')
serverJID = JID('pubsub.example.com')
password = 'secret'

application = service.Application('XMPP client')
xmppClient = client.XMPPClient(clientJID, password)
xmppClient.logTraffic = True
xmppClient.setServiceParent(application)

handler = MyClient(clientJID, serverJID, sys.stdin)
handler.setHandlerParent(xmppClient)

我用的是

代码语言:javascript
复制
twistd -noy sentry/myclient.tac < input.txt

下面是MyClient的代码:

代码语言:javascript
复制
import os
import sys
import time
from datetime import datetime

from wokkel.pubsub import PubSubClient

class MyClient(PubSubClient):
    def __init__(self, entity, server, file, sender=None):
        self.entity = entity
        self.server = server
        self.sender = sender
        self.file = file

    def loop(self):
        while True:
            line = self.file.readline()
            if line:
                print line
            else:
                from twisted.internet import reactor
                reactor.stop()

    def connectionInitialized(self):
        self.loop()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-03-17 20:48:52

代码语言:javascript
复制
from twisted.internet import reactor
reactor.stop()

那应该管用。这并不意味着您的应用程序有其他问题。我不知道你提供的信息有什么问题。

你能提供更多的代码吗?

编辑:

好的,现在的问题是,你没有停止你自己的while True循环,所以它会继续循环,最终再次停止反应堆。

试试这个:

代码语言:javascript
复制
from twisted.internet import reactor
reactor.stop()
return

现在,我怀疑您的循环对于事件驱动的框架来说不是件好事。虽然您只是打印行,这很好,但取决于您真正想要做什么(我怀疑您将做更多的工作,而不仅仅是打印行),您将不得不重构该循环来处理事件。

票数 7
EN

Stack Overflow用户

发布于 2016-04-20 08:49:26

使用reactor.callFromThread(reactor.stop)而不是reactor.stop。这应该能解决这个问题。

票数 6
EN

Stack Overflow用户

发布于 2012-11-24 04:24:46

我以前是这样做的(在一个称为应用程序的非扭曲处理程序中):

代码语言:javascript
复制
reactor.removeAll()
reactor.iterate()
reactor.stop()

我不能百分之百肯定这是正确的方式,但扭曲是快乐的

在tac中启动的同一个应用程序是由twistd信号处理程序直接处理的,我发现了这个问题,因为我有一些rpc客户端请求,在退出之前我需要等待和处理结果,看起来twistd只是在关闭反应堆而不让调用结束

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5344123

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档