[Twisted-Python] newbie: asynchronous client

Bob Ippolito bob at redivi.com
Mon Feb 17 17:14:27 MST 2003


On Monday, Feb 17, 2003, at 18:44 America/New_York, Jp Calderone wrote:

> On Mon, Feb 17, 2003 at 05:56:56PM -0500, Joshua Bloom wrote:
>>
>> I'd like to set up a non-blocking TCP client that loops indefinately,
>> waiting for the user to input something (which gets sent to the 
>> server)
>> but also responds to server replies whenever it can. So after I send
>> "factorial 1234" to the server, I'd like to be able to say "1 + 2" 
>> before
>> the server returns and get a response from that.
>>
>> Thanks in advance for any pointers.
>
>   Non-blocking user-input is the hardest part of this program.  That 
> said,
> if you go with one of the GUI toolkits that Twisted is integrated 
> with, it
> should be no problem (Qt, Gtk, Tk, PyUI, curses, wxWindows).  Their
> mainloops are mashed into Twisted's in various ways, letting network 
> and
> user events happily co-exist.  If you go with another toolkit, you'll 
> have
> to find some way to accomplish the same mainloop integration.
>
>   Examples for GUI apps are (surprise) in doc/examples/

Eh, if you're fine with line-based input (doesn't actually get data 
until user presses enter, and there's a way around that if necessary.. 
at least you can get around it in unix).  I've got some code below that 
you could use as a starting point.

I think that maybe there should be a tutorial on how to make 
interactive console Twisted programs using stdio and then another with 
curses/readline perhaps?

-bob

#!/usr/bin/env python
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor, stdio
class MyProtocol(LineReceiver):
	delimiter = '\n'
	def lineReceived(self, line):
		line = line.rstrip() # this sacrifices trailing white space and/or a 
possible '\r' if on windows?
		if line.lower() in ('quit', 'q'):
			reactor.stop()
		print "You just typed: %s" % (line,)

if __name__ == '__main__':
	# basically tie stdin to an instance of MyProtocol
	print 'type "q" or "quit" (sans quotes) to exit'
	stdio.StandardIO(MyProtocol())
	reactor.run()





More information about the Twisted-Python mailing list