[Twisted-Python] Getting a synchronous interface to a twisted reactor

Phil Mayers p.mayers at imperial.ac.uk
Thu Apr 22 03:21:30 EDT 2010

On 04/22/2010 07:06 AM, Andrey Fedorov wrote:
> Thanks! The main reason for the question, though, is just curiosity from
> playing with and learning the Twisted API, not necessarily getting the
> example working :)
> A more direct question would have been - is there a Twisted reactor
> which provides a blocking call instead of a callback? Is there an
> accepted "best" way of wrapping an non-blocking async API with callbacks
> into a blocking synchronous one?

If I understand what you're asking you want to call Twisted code in the 
following style:

def function():
   # this code blocks
   result = some_twisted_thing()
   value = process(result)
   final = morecode(value)

Rather than:

def function():
    def = some_twisted_thing()

If that's the case, then the answer is "sort of" but I think you might 
have misunderstood Twisted a bit. The entire point is to have 
non-blocking APIs, not to want a blocking API.

You can't "really" block, because that stops the reactor from running, 
and thus any networking events being handled.

You can emulate it in Python 2.5 with generators & a special decorator:

from twisted.internet import deferred

def function():
    result = yield some_twisted_thing()
    value = yield process(result)
    final = yield morecode(value)

I might have misunderstood what you're asking though, in which case I 
apologise, and can you be more specific?

More information about the Twisted-Python mailing list