Async callback in python

Sells, Fred fred at adventistcare.org
Wed Dec 6 13:55:05 EST 2006


the standard print gets "delayed" somewhere inside python, however if you
use

print >>sys.stderr, "whatever", 3, 4 5

that prints immediately, or so it seems to me.

-----Original Message-----
From: python-list-bounces+frsells=adventistcare.org at python.org
[mailto:python-list-bounces+frsells=adventistcare.org at python.org]On
Behalf Of Linan
Sent: Monday, December 04, 2006 11:18 PM
To: python-list at python.org
Subject: Async callback in python


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 :)

-- 
http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list