Newbie: how to wait for callbacks...

jeff.clough at gmail.com jeff.clough at gmail.com
Sat Oct 14 04:19:36 CEST 2006


On Oct 13, 12:38 pm, Jan Bakuwel <jan.baku... at int.greenpeace.org>
wrote:
> Hoi all,
>
> I'm trying to write a little code that waits for a callback routine to
> be called, ideally with a timeout...
>
> I guess the code below is not right (using a boolean flag), but since
> I'm new to Python, I don't know yet where the semaphores live and/or
> whether I'm on the right track...
>
> Any help is much appreciated...
>
> Jan
>
> def processEmail(emailMessage):
>
>     sendSent = False
>
>     def sendComplete(result):
>         print "Message sent successfully"
>         processEmail.sendSent = True
>     #end sendComplete
>
>     def sendFailed(error):
>         print >> sys.stderr, "Error", error.getErrorMessage()
>         processEmail.sendSent = True
>     #end sendFailed
>
>     if emailMessage.is_multipart():
>         print "...multipart"
>         for pl in emailMessage.walk():
>             pass
>     else:
>         print "...not multipart"
>     # simulate some processing that will take place here
>     time.sleep(1)
>
>     multiMessage = MIMEMultipart()
>     multiMessage['From'] = emailMessage['From']
>     multiMessage['To'] = emailMessage['To']
>     multiMessage['Subject'] = emailMessage['Subject']
>     messageData = multiMessage.as_string(unixfrom=False)
>     sending = smtp.sendmail('smtp', '... at t.t', '... at t.t', messageData)
>     sending.addCallback(sendComplete).addErrback(sendFailed)
>
>     while not processEmail.sendSent:
>         print "z"
>         time.sleep(0.1)
>     #end while
>
>     print "...done"
>     #raise smtp.SMTPDeliveryError(code=550, resp="Unable to deliver
> email, please try again later", isFatal=True, retry=False)
>     print ""
>     #endif
>
> #end ProcessEmail

For semaphores, check out the mutex module
(http://docs.python.org/lib/module-mutex.html). For timeouts, look at
the alarm signal in the signal module
(http://docs.python.org/lib/module-signal.html).

--Jeff




More information about the Python-list mailing list