mercredi 21 février 2007

[Python] Callback examples with FTP

From the wikipedia article:

In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a function defined in a higher-level layer.

Usually, the higher-level code starts by calling a function within the lower-level code passing to it a pointer or handle to another function. While the lower-level function executes, it may call the passed-in function any number of times to perform some subtask. In another scenario, the lower-level function registers the passed-in function as a handler that is to be called asynchronously by the lower-level at a later time in reaction to something.

Two examples with the FTP module of Python:

from ftplib import FTP

ftp = FTP("the_host")
ftp.login('ftpuser', 'ftppass')
ftp.cwd("folder")

# To obtain the list of files in a variable (not just the standard output) :

fileList=[]
command=ftp.retrlines("LIST",fileList.append)

# To download the file :

file = open("myfile.exe", 'wb')
ftp.retrbinary("RETR myfile.exe",file.write)
ftp.quit()
file.close()

Aucun commentaire: