[Twisted-Python] Blocking

Moshe Zadka m at moshez.org
Tue May 6 04:10:55 MDT 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.addCallback(succ.append)
    d.addErrback(fail.append)
    d.addBoth(lambda _: reactor.stop())
    reactor.run()
    if succ:
        return succ[0]
    else:
        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()
1052215780.7
hello world
1052215790.71

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