Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python - How to quit an asyncore dispatcher from a handler?

I couldn't find this in the docs, but how am I meant to break out of the asyncore.loop() without using signals?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That was quick to work out after looking at the source code. Thanks to the docs for linking directly to the source!

There is an ExitNow exception you can simply raise from the app, which exits the loop.

Using the EchoHandler example from the docs, I've modified it to quit immediately when receiving data.

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            raise asyncore.ExitNow('Server is quitting!')

Also, keep in mind that you can catch ExitNow so your app doesn't raise if you're using it internally. This is some of my source:

def run(config):
    instance = LockServer(config)
    try:
        asyncore.loop()
    except asyncore.ExitNow, e:
        print e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...