Twisted interactive console
As you all already know TwistedMatrix is great to write asynchronous event-driven network oriented programs: define how your protocol responds in case of events, attach some callbacks if you need them, wrap it in a factory and activate the reactor.
The reactor runs a giant loop in which events are processed in a non-blocking fashion. Sometimes, though, everything a man needs it’s just to make it stop. At least for a while, at least for the sake of getting data from the user.
The most prominent example of a command line client program that needs to stop and wait is a REPL. The following kind ofREPL is a bit unorthodox, you’ll see.
When the protocol it is connected to the standard output with
the program displays the prompt, hence when a line is received from the standard input it is sent to the other protocol attached on the network and a callback is registered for the response. I also decided to use less to display the response if it’s more than some lines but that’s a detail.
The sendCmd function instantiate the networked protocol and its factory:
Then, when the server replies with some content we check to see if everything went ok and the reconstruct the whole response sending it back the REPL:
How cool is that? Not really to be honest. It has a big gigantic fault: every time you input a line a connection to the server is opened and closed. That’s bad, really bad.
It didn’t take too long to create a version that use just one connection:
We store the connector and the factory. issueCommand does not open a connection anymore, just:
We write directly to the transport of the connector (and not the one connected to the stdout) and register the callback on the factory’s deferred.
That’s better in my opinion and a nice start. I know that within twisted.conch.stdio there’s something more evolved. I’ll try to look into it when I have more time.
What do you think about this try?