[Twisted-Python] Tie two event loops

glyph at divmod.com glyph at divmod.com
Wed Jul 2 13:18:05 MDT 2008


On 02:46 pm, paulalexwilson at gmail.com wrote:
>I'm creating a server that accepts client connections and then drives
>the client according to a simple, line-oriented protocol. The server
>sends the request (1 line), and receives a single lined result. I'd
>like the server to offer an API to generate the correct request lines
>to the client, and return the results (either blocking or
>asynchronously). So in effect, I have two event loops, one from the
>Network and one from whatever's sending the API requests (command
>line?).

>Can anyone offer any guidance on how to tie these two parts together?

As you are new to Twisted, I would strongly recommend ignoring the 
"either blocking or asynchronously" part, and simply return the results 
asynchronously, in a Deferred.  It's *possible* to do what you want, but 
to really understand what's going on well enough to pull it off you need 
to be pretty well-versed in the event-driven programming model, as well 
as gnarly implementation specifics of Twisted itself.  In my experience, 
most places that people think that they want async+sync interfaces to 
something, they actually just want async+convenient.  Here are some ways 
you could get some benefits of a synchronous API without actually having 
one:

If you are talking about generating requests from an interactive Python 
interpreter, you might consider using the interpreter bundled with 
Conch.  Try invoking it with 'python -m twisted/conch/stdio'.  This 
command line will notice when it receives a Deferred and display a 
result when it arrives.

If you are talking about your *own* command line, consider using 
twisted.internet.stdio.StandardIO to get it to communicate with the main 
event loop.

If this isn't really about command-lines but you want to write little 
"scripts" that have extended conversations with a client and process 
lots of different results, consider using the 
twisted.internet.defer.inlineCallbacks decorator with Python 2.5 
generators.  This syntactic convenience will let you avoid defining 
functions to handle callbacks, and will therefore shorten certain kinds 
of code.

I hope one of those solutions helps!




More information about the Twisted-Python mailing list