gpt4 book ai didi

python - 如何优雅地退出使用 twistd 启动的应用程序?

转载 作者:太空狗 更新时间:2023-10-29 17:46:59 26 4
gpt4 key购买 nike

我有一个 jabber 客户端,它正在读取其标准输入并发布 PubSub 消息。如果我在 stdin 上收到 EOF,我想终止客户端。

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

from twisted.internet import reactor
reactor.stop()

导致 exceptions.AttributeError: 'module' object has no attribute 'stop'

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

编辑 2

最初的问题是由一些符号链接(symbolic link)弄乱了模块导入引起的。解决该问题后,我得到一个新的异常:

twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.

异常发生后,twistd 关闭。我认为这可能是由于在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

这是 MyClient 的代码:

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()

最佳答案

from twisted.internet import reactor
reactor.stop()

应该 工作。事实上,这并不意味着您的应用程序存在其他问题。我无法从您提供的信息中找出问题所在。

你能提供更多(全部)代码吗?


编辑:

好的,现在的问题是您没有停止自己的 while True 循环,因此它将继续循环并最终再次停止 react 器。

试试这个:

from twisted.internet import reactor
reactor.stop()
return

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

关于python - 如何优雅地退出使用 twistd 启动的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5344123/

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