[Twisted-Python] Problem exiting script that calls a func returning a called deferred

Amaury Forgeot d'Arc amauryfa at gmail.com
Fri Apr 25 05:27:58 EDT 2008


Terry Jones wrote:
> >From searching and reading the list archives, I know the following comes up
>  under various guises, and although I think I understand what's going on, I
>  don't see a nice solution.
>  I'm trying to write a standalone script. It calls externalFunc, a function
>  someone else wrote that returns a deferred. My script could look something
>  like this:
>     from twisted.internet import reactor
>     from twisted.python import log
>     if __name__ == '__main__':
>         def ok(result):
>             print "ok called with", result
>         def nok(failure):
>             print "nok called with", failure
>             return failure
>         def stop(x):
>             reactor.stop()
>         d = externalFunc()
>         d.addCallback(ok)
>         d.addErrback(nok)
>         d.addBoth(stop)
>         d.addErrback(log.err)
>         reactor.run()
>  And that works fine.
>  Now suppose I want to do some testing in which I swap out the external
>  function for a library I wrote myself (or for another implementation).  In
>  the testing library, externalFunc is simplified and uses defer.success() to
>  return its result.
>  In this case the script raises RuntimeError, "can't stop reactor that isn't
>  running" because the deferred that comes back from externalFunc has already
>  been called. So when I add the call/errbacks, they are fired right away and
>  the reactor isn't running when the stop function tries to stop it.
>  And script never exits because it then starts the reactor.

did you try something like:

       def stop(x):
           reactor.callLater(0, reactor.stop)

This ensures that the reactor is started before you tell it to stop.

Amaury Forgeot d'Arc

More information about the Twisted-Python mailing list