[Tutor] How to define a callback

Terry Carroll carroll at tjc.com
Thu Dec 11 18:41:03 EST 2003


On Thu, 11 Dec 2003, "Héctor Villafuerte D." wrote:

> I'm using the ftplib module and need to look for certain
> files. I'm planning on using string.find on the output of
> LIST. The question is: how to define a callback for the
> ftplib function retrlines? i.e. I don't want to print to
> sys.stdout, I want to print to a string.


Here's an example of using a callback w/ftplib.  I used this as a 
proof-of-concept for an approach I never went through on on a particular 
project:

#########
import ftplib

server = "ftp.fu-berlin.de"
remote_dir = "/pub/misc/movies/database/"
local_dir = "./IMDB-gzfiles/"
filename = "ratings.list.gz"


def mycallback(parm):
#    print "rec'ved ", len(parm), "bytes."
    outfile.write(parm)

outfile = open(local_dir+filename,"wb")

f = ftplib.FTP(server)
resp = f.login()
print resp
resp = f.cwd(remote_dir)
print resp
resp = f.retrbinary("RETR "+filename, mycallback)
print resp
resp = f.quit()
print resp

#########

(You can delete the "print resp" statements, they just make me feel 
bette as I watch.)

Basically, when you call f.retrbinary, it will call the routine mycallback 
every time it receives data.  In my routine, I simply write that data out 
to the file; but you can do something else, like append it to a string, if 
you want.

This is a binary call, but it's basically the same idea for a non-binary 
calll (your retrlines).

-- 
Terry Carroll
Santa Clara, CA
carroll at tjc.com 




More information about the Tutor mailing list