1

I've just rewritten something akin to a basic python server ( https://docs.python.org/3/library/socketserver.html ) because I thought I needed to.

My question is, did I?

What I wanted to do is break out of the handler and out of the server loop if a certain request is received (a stop-the-server request, if you will). Originally, I tried to break out of the server loop by throwing an exception, but it turns out the way the socketserver handlers are run is inside of a "try catch-all expect" block, which means exceptions thrown inside of a handler won't ever propagate beyond the handler invoking function (the one with the catch-all exception block).

So does python has a longjump mechanism that can pierce a try-catch_all-expect block or could I run the serve_forever_loop inside a thread and then, from the handler, do something like Thread.current.kill() (how can I do this?).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 1
    Why can't you subclass and provide your own `handle_error`? – John La Rooy Apr 22 '15 at 06:57
  • @JohnLaRooy The BaseServer class doesn't pass the error to handle_error, just the request (already read from) and the client_address https://hg.python.org/cpython/file/3.4/Lib/socketserver.py . I would only need to break out of the loop on a certain type of error (my custom type). – Petr Skocik Apr 22 '15 at 07:44

1 Answers1

1

As far as I know, there is no way to skip stack frames when you raise an exception.

But if you really need this functionality, you can find other ways for one part of your code to send messages to another part. If both the handler and server are running in the same interpreter instance (i.e. not in separate threads), you can have the handler change some variable accessible to the main server loop, which the server loop checks for. If you're in different interpreters, you could have the handler write to a log file that the server loop watches. The log file idea is kind of hackish, but logging is a good thing to have for servers anyway.

jack
  • 2,094
  • 1
  • 19
  • 17