我有一个叽叽喳喳的客户,正在阅读它的stdin并发布PubSub消息。如果我在stdin上得到EOF,我想终止客户端。
我第一次尝试sys.exit()
,但这会导致异常,客户端不会退出。然后我做了一些搜索,发现我应该调用reactor.stop()
,但我无法使此工作。我的客户中的以下代码:
from twisted.internet import reactor
reactor.stop()
导致exceptions.AttributeError: 'module' object has no attribute 'stop'
我需要做什么才能使Twisted关闭并退出我的应用程序?
编辑2
最初的问题是由于一些符号链接扰乱了模块导入。在解决了这个问题之后,我得到了一个新的异常:
twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.
异常发生后,Twisted关闭。我认为这可能是由于在MyClient.connectionInitialized
中调用MyClient.loop
引起的。也许我需要把电话推迟到晚些时候?
编辑
这是我客户的.tac
文件
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)
我用它来调用
twistd -noy sentry/myclient.tac < input.txt
这是我客户的代码:
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()
使用
reactor.callFromThread(reactor.stop)
而不是reactor.stop
。这应该能解决问题。这应该有效。事实上,这并不意味着你的应用程序有其他问题。我无法从你提供的信息中找出问题所在。
你能提供更多的代码吗?
编辑:
好吧,现在的问题是你没有停止你自己的循环,所以它会继续循环,最终再次停止反应堆。
试试这个:
现在,我怀疑您的循环对于事件驱动框架来说不是一件好事。当您只是打印行时,这是很好的,但是根据您真正想做的事情(我怀疑您将做的不仅仅是打印行),您必须重构该循环才能处理事件。
我以前是这样做的(在一个非扭曲的调用应用程序的sigint处理程序中):
我不是百分之百确定这是正确的方法,但是twisted很高兴
在tac中启动的同一个应用程序由twistd信号处理程序直接处理,我发现这个问题是因为我有一些rpc客户机请求,我想在退出之前等待并处理结果,看起来twistd只是在不让调用完成的情况下终止反应器
相关问题 更多 >
编程相关推荐