[Twisted-Python] Blocking

Moshe Zadka m at moshez.org
Tue May 6 06:10:55 EDT 2003

In short command-line scripts, it's often much easier to block, especially
if the script doesn't need to do any serving. However, Twisted's API is
always non-blocking, returning deferreds. Here's a short function that
allowes more natural usage from scripts:

def makeBlocking(d):
    succ, fail = [], []
    d.addBoth(lambda _: reactor.stop())
    if succ:
        return succ[0]
        raise fail[0].value

Here's a short usage example:

>>> from twisted.internet import defer, reactor
>>> def callIn10():
...     d = defer.Deferred()
...     reactor.callLater(10, d.callback, "hello world")
...     return d
>>> import time
>>> print time.time();print makeBlocking(callIn10());print time.time()
hello world

This is especially useful in scripts which want to do pb calls, as currently
there is no way to do pb calls in a synchronous manner.

Moshe Zadka -- http://moshez.org/
Buffy: I don't like you hanging out with someone that... short.
Riley: Yeah, a lot of young people nowadays are experimenting with shortness.
Agile Programming Language -- http://www.python.org/

More information about the Twisted-Python mailing list