Async callback in python

tleeuwenburg at gmail.com tleeuwenburg at gmail.com
Mon Dec 4 23:27:54 EST 2006


Did you flush the buffer?

It might be that the print statements are being called in the order you
expect but that they are all written to the screen only at the end.
I've had that happen before.

Cheers,
-T

Linan wrote:
> Hi,
>
> In javascript, code could be written like this:
>
> ...
>
> 	var _p=XMLHttpRequest();
> 	_p.open('GET',url,true);
> 	_p.send(null);
> 	_p.onreadystateChange=function(){
> 		if(_p.readyState==4)
> 			cb(_p.responseText);
> 	}
> ...
>
> This basic AJAX code allows function to be called when it's invoked,
> without blocking the main process. There is same library asyncore in
> python. However, I can't validate it's asynchronous through code:
> class T(asyncore.dispatcher):
> 	def __init__(self,host,url):
> 		asyncore.dispatcher.__init__(self)
> 		self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
> 		self.connect((host,80))
> 		self.url='GET %s HTTP/1.0\r\n\r\n' % url
>
> 	def handle_connect(self):
> 		pass
>
> 	def handle_close(self):
> 		self.close()
>
> 	def handle_read(self):
> 		print 'READING.....'
> 		print self.recv(256)
>
> 	def handle_write(self):
> 		sent=self.send(self.url)
> 		self.url=self.url[sent:]
>
> t=T('aVerySlowSite','/')
> asyncore.loop()
> for i in range(0,10):
> 	print '%d in main process' % i
> 		time.sleep(1)
>
> Suppose it's asynchronous, couple of '%d in main process' lines should
> be mixed in the output of T.handle_read(), right? But I found that
> actually main process was blocked at asyncore.loop(), until the the
> socket was closed. My questions:
> 1, Did I do anything wrong?
> 2, Is it real asynchronous?
> 3, If not, where to get the real one(s)?
> 
> Any comment is welcome :)




More information about the Python-list mailing list