Search code examples
pythontwistedpython-interactive

twisted run asynchronous examples and make connections at Python prompt?


The ldaptor project has some example Twisted-based code at an interactive Python prompt. At one point [1], though, the example breaks if you actually try to follow along at the prompt because a function was deprecated-- twisted.trial.util.deferredResult(). What was interesting is that this apparently let the reactor run, the connection established, and the deferred result (an LDAPClient protocol instance) is returned which could be manipulated within the interactive Python interpreter.

My question is, is there any modern way to do this sort of thing for the sake of examples or just experimenting? I can do something like this at the prompt:

>>> from ldaptor.protocols.ldap.ldapclient import LDAPClient
>>> from twisted.internet import reactor
>>> from twisted.internet.endpoints import clientFromString, connectProtocol
>>> e = clientFromString(reactor, "tcp:host=localhost:port=10389")
>>> e
<twisted.internet.endpoints.TCP4ClientEndpoint at 0xb452e0c>
>>> d = connectProtocol(e, LDAPClient)
>>> d
<Deferred at 0xb34656c>

But I can't think of any way to run the rector an return the deferred result to the interactive prompt. Is it possible? Would the crochet project help?

[1] https://ldaptor.readthedocs.org/en/latest/addressbook-example.html#searching


Solution

  • You might try:

    • python -m twisted.conch.stdio
    • pip install bpython urwid; bpython-urwid --reactor select

    Each of these will give you an enhanced Python prompt with a Twisted reactor running in the background. The former supports Deferreds natively, but the latter is much more feature-rich.