473,804 Members | 3,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Async callback in python

Hi,

In javascript, code could be written like this:

....

var _p=XMLHttpReque st();
_p.open('GET',u rl,true);
_p.send(null);
_p.onreadystate Change=function (){
if(_p.readyStat e==4)
cb(_p.responseT ext);
}
....

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.disp atcher):
def __init__(self,h ost,url):
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.connect((h ost,80))
self.url='GET %s HTTP/1.0\r\n\r\n' % url

def handle_connect( self):
pass

def handle_close(se lf):
self.close()

def handle_read(sel f):
print 'READING.....'
print self.recv(256)

def handle_write(se lf):
sent=self.send( self.url)
self.url=self.u rl[sent:]

t=T('aVerySlowS ite','/')
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 2794
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=XMLHttpReque st();
_p.open('GET',u rl,true);
_p.send(null);
_p.onreadystate Change=function (){
if(_p.readyStat e==4)
cb(_p.responseT ext);
}
...

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.disp atcher):
def __init__(self,h ost,url):
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.connect((h ost,80))
self.url='GET %s HTTP/1.0\r\n\r\n' % url

def handle_connect( self):
pass

def handle_close(se lf):
self.close()

def handle_read(sel f):
print 'READING.....'
print self.recv(256)

def handle_write(se lf):
sent=self.send( self.url)
self.url=self.u rl[sent:]

t=T('aVerySlowS ite','/')
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*******@gmai l.comwrote:
Hi,

In javascript, code could be written like this:

...

var _p=XMLHttpReque st();
_p.open('GET',u rl,true);
_p.send(null);
_p.onreadystate Change=function (){
if(_p.readyStat e==4)
cb(_p.responseT ext);
}
...

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.disp atcher):
def __init__(self,h ost,url):
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.connect((h ost,80))
self.url='GET %s HTTP/1.0\r\n\r\n' % url

def handle_connect( self):
pass

def handle_close(se lf):
self.close()

def handle_read(sel f):
print 'READING.....'
print self.recv(256)

def handle_write(se lf):
sent=self.send( self.url)
self.url=self.u rl[sent:]

t=T('aVerySlowS ite','/')
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 "asyncronou s" 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 "asyncronou s" 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*******@gmai l.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('aVerySlow Site','/')
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********@gma il.comwrote:
On 4 Dec 2006 20:18:22 -0800, Linan <ta*******@gmai l.comwrote:
Hi,

In javascript, code could be written like this:

...

var _p=XMLHttpReque st();
_p.open('GET',u rl,true);
_p.send(null);
_p.onreadystate Change=function (){
if(_p.readyStat e==4)
cb(_p.responseT ext);
}
...

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.disp atcher):
def __init__(self,h ost,url):
asyncore.dispat cher.__init__(s elf)
self.create_soc ket(socket.AF_I NET, socket.SOCK_STR EAM)
self.connect((h ost,80))
self.url='GET %s HTTP/1.0\r\n\r\n' % url

def handle_connect( self):
pass

def handle_close(se lf):
self.close()

def handle_read(sel f):
print 'READING.....'
print self.recv(256)

def handle_write(se lf):
sent=self.send( self.url)
self.url=self.u rl[sent:]

t=T('aVerySlowS ite','/')
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 "asyncronou s" 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 "asyncronou s" 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
7145
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 threads are complete, the call the Callback method. Each "thread" calls the same callback method. What thread does this callback method exist on? My testing indicates the
6
1937
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. Now I was looking at the Async WaitHandle options. They are "WaitOne", "WaitAny", and "WaitAll". I would like to process all of the results that are returned. However, due to network performance and other factors not all of the results are...
10
2967
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 exactly what I want. Here are my goals 1. I would like the IAsyncResult that is returned by the Begin function to be able to be waited on or polled to check for completion. 2. The Begin function would take a callback, and the async process would
6
1826
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 unloads. When the callback method is raised, only the method in the web page is run and the page never refreshes, it seems it all happens on the server side. I am trying to refresh the constrols on the page inside the callback method, but when id...
11
6974
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 making the main thread sleep until the counter gets back to zero. The call back function for each call decrements the counter. Is there a better way to make the thread wait until all calls are complete besides using the counter? I've seen some things...
5
3261
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 btnUpload_Click(object sender, System.EventArgs e) { try { SOPWebService.Client uploader = new
6
3827
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 cause these to block? 2) You can connect together a binaryreader to a networkstream:
15
8416
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 (asynchronously). Then it repackages these UDP packets and sends them to a subscriber via TCP. Now, I can read the UDP stream all day long without the application
10
4518
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 consideration here is that it is supplied to the AsyncOperationManager.CreateOperation(userSuppliedState) method... with userSuppliedState being, more or less, a taskId. In this case, the userSuppliedState {really taskId} is of the object type,...
3
2545
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 WebService, calling its method "FooMethod(...args...)". I've imported the web reference within my VisualStudio project and tryed to invoke the method. I noticed that the intellisense expose also: - an "AsyncFooMethod(...args...(+1 overloads))";
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10567
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10310
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9138
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7613
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6847
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3809
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2983
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.