Exiting a program from within an object method.
Alex Martelli
aleaxit at yahoo.com
Thu Jan 4 11:26:09 EST 2001
"Benjamin Scherrey" <scherrey at innoverse.com> wrote in message
news:9325ne014j at news2.newsguy.com...
> I've written a small python program that instantiates an object
which
> inherits from SocketServer.BaseRequestHandler. The __main__ function
starts
> this thing up with the serve_forever() method. Inside the handle() method
> of my object I check for a command to shutdown and, if received, call
> sys.exit(0). All this does is generate a SystemExit exception and does not
> terminate my program. Even if I wrap the call to serve_forever() with a
> try: except: block, the exception is not caught. I presume because the
> object's handle() method is possibly being executed in a child thread and
> python must not support cross thread exception handling (I'm not
> instantiating any threads explicitly, I'm assuming that the
> BaseRequestHandler is doing this internally)?
I think it's simpler than that -- your handle method is being called
by the TCPServer's process_request method, which, in turn, is in a
try/except that catches ALL exceptions:
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
and, by default, handle_error prints a traceback but does not
terminate.
> What's a simple way to have my object exit the application
cleanly?
I suspect the simplest way is: inherit from TCPServer and override
the handle_error method, so that (e.g.) a SystemExit, only, will
be re-raised. I am, however, not sure about how this may interact
with possible threading, and I DO know a request executed in
another process won't be able to communicate this way...! So, IF
you're using a Forking or Threading server, you may need to use
another 'termination-indicator', which your handle() method can
set (e.g., create a file with a distinguished and pre-agreed
name!), and you will also override serve_forever to to periodic
checks on that termination-indicator.
But there's no need for this extra complexity if you're not
forking (or, possibly, threading).
Alex
More information about the Python-list
mailing list