How to capture stdout into a string?

Peter Hansen peter at engcorp.com
Sun Jun 9 19:38:13 CEST 2002


Michael Davis wrote:
> 
> Hi,
> 
> I'm using libftp. The FTP.dir() function gets the remote directory listing
> and prints it to standard out. How can I capture that in a string?
> 
> If I were using an external process, I know I could open a pipe to it. But
> it's not an external process.
> 
> I'm sure there's a tricky way of doing it by getting the file descriptor for
> stdout and reading from it directly, but I was hoping to avoid going that
> low-level. I will if I must though.

The best option by far (and really the easiest) to figure out
stuff like this is to check the source.

In this case, you can see that dir() calls retrlines() with
the LIST argument and no callback function.  As the notes
say, this directs the output to stdout.

You must specify a callback function of some kind.  The best
is probably a small class with a __call__ method, but this
little baby seems to work too, although it may not be quite
enough to work in the general case yet.  It grabs lines that
are passed to it into a list, until it is called with an
empty argument, at which point it returns the saved list
and deletes it, ready for another bunch of lines:

>>> def grablines(line='', lines=[]):
...    if line:
...       lines.append(line)
...    else:
...       result = lines[:]
...       del lines[:]
...       return result
...
>>> grablines()
[]
>>> grablines('test')
>>> grablines('test')
>>> grablines('test')
>>> grablines()
['test', 'test', 'test']
>>> ftp.dir(grablines)
>>> grablines()
['total 62', '-rw-r--r--  1 engcorp  netdial      0 Jan 11  2000 .addressbook',
'-rw-------  1 engcorp  netdial   2285 Jan 11  2000 .addressbook.lu', '-rw------
-  1 engcorp  netdial   6459 May 21 23:42 .bash_history', '-rw-r--r--  1 engcorp
  netdial     29 Jun 17  2001 .forward', '-rw-------  1 engcorp  netdial  12221
.............]


-Peter



More information about the Python-list mailing list