[Twisted-Python] Multiple clients

Kevin Horn kevin.horn at gmail.com
Fri Jun 18 18:24:10 EDT 2010

On Fri, Jun 18, 2010 at 12:55 PM, Szabolcs Balogh <bszabolcs at gmail.com>wrote:

> It is possible to:
>  - start the reactor when I initialize my program (eg. in main)
>  - call connectTCP or connectSSL when I want and every time I want?
Yes, this is exactly what you are supposed to do.  Call the reactor _once_
and once only.

The call connectTCP or whatever whenever is appropriate for your program.

> Something like this:
> def check_messages(account):
>        # connect to imap server and check for new mailboxes/messages
>        reactor.connectSSL(...)
> if __name__ == "__main__":
>        reactor.run()
>        check_message(account1)
>        check_message(account2)
>        ...
>        do something else
>        ...
>        check_message(accountn)
> Because I can't implement this :}
> I have started the implementation based on "Twisted Network Programming
> Essential", but this book doesn't treat multiple connections...
The above won't work, because run() blocks.  So in your example here,
check_messages() won't be called until after the run() call returns, which
means the reactor won't be running, which means check_messages won't work.

look into callWhenRunning:

and do something like:

def start_checking():
    (do your check_messages stuff here)

if __name__ == '__main__':


using callWhenRunning isn't necessary, but I find that it clarifies things
for me sometimes

reactor.run() is usually the _last_ thing I call in my Twisted programs,
unless I have some shutdown cleanup to do, and even that is usually better
done in the reactor shutdown hook

you also need to figure out how to structure your program flow using
deferreds, which is not always easy, and depends greatly on your specific

remember that deferreds are just a way of organizing callback functions

you can "chain" deferreds something like this (assuming your functions
return Deferreds):

d = check_first_one()
d.addCallback(check_second_one, ...)


which will make check_second_one start after check_first_one completes

You can also use a deferredList, which is often handy when you want to keep
track of several deferred operations which are operating simultaneously
(I haven't used one in a while, so I don't have a simple example off the top
of my head, but there's a simple example in the Twisted book)

Hope this helps,

Kevin Horn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20100618/f9335a51/attachment.htm 

More information about the Twisted-Python mailing list