[Tutor] How to define a callback

Daniel Ehrenberg littledanehren at yahoo.com
Sat Dec 13 15:50:42 EST 2003


--- "Héctor_Villafuerte_D." wrote:
> Hi all!
> 
> 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.
> 
> 
> retrlines(command[, callback])
>    Retrieve a file or directory listing in ASCII
> transfer mode.
>    command should be an appropriate "RETR" command
> (see retrbinary())
>    or a "LIST" command (usually just the string
> 'LIST').
>    The callback function is called for each line,
> with the trailing
>    CRLF stripped. The default callback prints the
> line to sys.stdout.
> 
> 
> Thanks for your help.

What you need to do is make a class that emulates
sys.stdout but then change the .write() function to
use a string instead. Here's a minimalistic example of
how to do that:

>>> class strout(object):
...     def __init__(self, string=''):
...         self.string = string
...     def write(self, newstring):
...         self.string += newstring
...     __str__ = lambda self: self.string

You can also have it go to a list, which I think would
be more convienent:

>>> class listout(object):
...     def __init__(self, string=''):
...         self.list = []
...     def write(self, newstring):
...         self.list.append(newstring)
...     __str__ = lambda self: str(self.list)

I can't figure out how to make these inherit from the
str or list classes, which would make it much more
convienent.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
New Yahoo! Photos - easier uploading and sharing.
http://photos.yahoo.com/



More information about the Tutor mailing list