[Twisted-Python] Need Exception that will stop ther reactor within twistd

glyph at divmod.com glyph at divmod.com
Sat Nov 25 00:39:21 EST 2006


On 12:55 am, ncesar at lunix.com.ar wrote:

>> This is bad form, however.  Particular types of exception should not stop
>> the reactor.  Code that wants the reactor to stop, should call
>> reactor.stop.  Maybe you could make a method that both calls reactor.stop()
>> *and* raises an exception.
>
>This is the way i'm doing it right now, but i'm starting to detect new
>exceptions raised within standard library (among others) code... and instead
>of catching all posibilities I wanted the application to quit (with the
>corresponding logging done).
>
>I was wondering if twistd/the application class could have a "exit on
>Exception" for this type of operations.

In general this is a bad idea.  There are basically 3 kinds of code you can write with Twisted:

  1. Infrastructure code, which implements a protocol and provides APIs for parsing and dealing with events.  This kind of code should never contain a reactor.stop at all.
  2. Application code which exits in response to a particular user event.  This kind of code should contain exactly 1 call to reactor.stop, in the handler for the user event that is the explicit stop.
  3. Programs which do one operation, then stop themselves.  This kind of code should contain exactly 1 call to reactor.stop, in the final callback/errback of the Deferred representing the operation that it is run to perform.

It sounds like you are writing code of type 3.  I'm guessing you're writing a program which does one thing, then shuts itself down.  If that is the case, the "program" should be encapsulated by a Deferred, and there should be a final addBoth which waits for the program to finish when it exits.

If you *don't* structure your program this way, then you'll discover later that sometimes, you want to run your particular operation TWICE in the lifetime of the process instead of once, and you will have to deal with dozens of calls to reactor.stop littered around your application in lots of places.  Don't try to always stop the *process* when your program is complete: stop the *program* by keeping a Deferred around which represents its complete run.  That way the *driver* for the program is responsible for stopping it, and when you want to aggregate multiple runs of it, you can easily use a tool like DeferredList, or do something different in the callbacks at the end.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20061125/03300822/attachment.htm 


More information about the Twisted-Python mailing list