[Twisted-Python] Handling errors when using deferToThread

Pedro Sanchez psanchez at nortel.com
Fri Oct 28 08:35:08 MDT 2005


Hello,

In the twisted documentation there is this example:


from twisted.internet import threads
def doLongCalculation():
    # .... do long calculation here ...
    return 3

def printResult(x):
    print x

# run method in thread and get result as defer.Deferred
d = threads.deferToThread(doLongCalculation)
d.addCallback(printResult)


This works well as long as doLongCalculation() doesn't fail for
any reason. But if it does, how can it trigger an errBack?
I want to do something like this:

from twisted.internet import threads
def doLongCalculation():
    try:
       # .... do long calculation here ...
    except:
       < what can I return here to tell that
         the calculation failed? >
    return 3

def printResult(x):
    print x

def badResult(failure):
    print "Calculation failed!"

# run method in thread and get result as defer.Deferred
d = threads.deferToThread(doLongCalculation)
d.addCallbacks(printResult, badResult)


Thanks in advance for your help,

-- 
Pedro







More information about the Twisted-Python mailing list