473,396 Members | 1,961 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

Dec 5 '06 #1
5 2781
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 :)
Dec 5 '06 #2
On 4 Dec 2006 20:18:22 -0800, Linan <ta*******@gmail.comwrote:
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/
Dec 5 '06 #3
On 4 Dec 2006 20:18:22 -0800, Linan <ta*******@gmail.comwrote:
3, If not, where to get the real one(s)?
After reading Calvin's mail, you may want to see
http://twistedmatrix.com/ . It's an assynchronous library built around
the concept of deferreds (think of callbacks). You may like it =).

Cya,

--
Felipe.
Dec 5 '06 #4
At Tuesday 5/12/2006 01:18, Linan wrote:
>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?
No. As you noticed, asyncore.loop (without arguments) won't return
until all channels are closed.
>But I found that
actually main process was blocked at asyncore.loop(), until the the
socket was closed.
Exactly.
>My questions:
1, Did I do anything wrong?
2, Is it real asynchronous?
3, If not, where to get the real one(s)?
Perhaps you didn't understand the nature of asyncore processing. The
idea is not to have many threads, each one blocking on its own
(synchronous) socket processing. Instead, using a single thread which
never blocks, and dispatches events to many instances, each one
processing its own data.
If you want to do other things mixed with network events, put those
things inside the loop, that is, instead of asyncore.loop() do something like:

while asyncore.socket_map:
asyncore.loop(1, count=1)
// do other things
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Dec 5 '06 #5
On 12/4/06, Calvin Spealman <ir********@gmail.comwrote:
On 4 Dec 2006 20:18:22 -0800, Linan <ta*******@gmail.comwrote:
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/)
In addition to the above, you misinterpret the way the posted
JavaScript works. JavaScript uses a "run to completion" model and, in
browsers, is purely event-based. There is no "main process" to block,
and if you simulate one via a loop, the code you posted won't work.

Except in IE, because it violates the ecmascript standard and will
'call back' from the implementation to the javascript environment
without regard for the current state of that environment.
Dec 6 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: scott ocamb | last post by:
hello I have implemented a solution using async methods. There is one async method that can be invoked multiple times, ie there are multiple async "threads" running at a time. When these...
6
by: Amy L. | last post by:
I am working on a project where I will have a ton of async DNS calls in a console application. I would like to process the results of the Aync calls on the same thread that made the async call. ...
10
by: Shawn Meyer | last post by:
Hello - I am trying to write a class that has an async BeginX and EndX, plus the regular X syncronous method. Delegates seemed like the way to go, however, I still am having problems getting...
6
by: TS | last post by:
Im in a web page and call an asynchronous method in business class. the call back method is in the web page. When page processes, it runs thru code begins invoking the method then the page...
11
by: ryan | last post by:
Hi, I've omitted a large chunk of the code for clarity but the loop below is how I'm calling a delegate function asynchronously. After I start the each call I'm incrementing a counter and then...
5
by: Paul Hasell | last post by:
Hi, I'm trying to invoke a web method asynchronously but just can't seem to get it to tell me when it has finished! Below is the code I am (currently) using: private void...
6
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to...
15
by: dennis.richardson | last post by:
Greetings all. Here's a problem that's been driving me nuts for the last 48 hours. I'm hoping that someone has come across this before. I have a C# Application that reads a UDP broadcast...
10
by: Frankie | last post by:
It appears that System.Random would provide an acceptable means through which to generate a unique value used to identify multiple/concurrent asynchronous tasks. The usage of the value under...
3
by: Giulio Petrucci | last post by:
Hi there, I'm quite a newbie in Web Service programming/using and I'm sorry if my question could sound quite "stupid". ;-) I'm working on an application which should request a service to a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.