Async callback in python

Calvin Spealman ironfroggy at gmail.com
Tue Dec 5 00:15:29 EST 2006


On 4 Dec 2006 20:18:22 -0800, Linan <tali.wang at gmail.com> 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 :)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

You seem to be confusing the terms "asyncronous" and "threaded".
Although multi-threading is a way to implement asyncronous software,
it is not the only or the best way to get those results. Usually the
term "asyncronous" is attached to non-threaded methods, because
"multi-threading" is usually just used for those threaded methods.

Thus, solutions like asyncore are ways to allow asyncronous code
without threading, and usually this involves a loop, as with asyncore,
and until all the asyncronous operations running in the loop are
complete, the loop does not end.

If you wanted to have these prints interlaced in the http download,
you might schedule them as a seperate asyncronous operation.

I hope that helped.

PS - Another, more complete asyncronous framework is the Twisted
project (http://www.twistedmatrix.com/)

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/



More information about the Python-list mailing list