Copy Stdout to string

Gerard Flanagan grflanagan at gmail.com
Tue Apr 1 16:36:07 CEST 2008


On Apr 1, 4:03 pm, sophie_newbie <paulgeele... at gmail.com> wrote:
> Hi, I'm wondering if its possible to copy all of stdout's output to a
> string, while still being able to print on screen. I know you can
> capture stdout, but I still need the output to appear on the screen
> also...
>
> Thanks!

I don't know if it's what you want, but if you're talking about the
output of a single command, then the following (or a variation) should
do. (using 'svn info' as the command).

---------------------------------------------------
import subprocess
from cStringIO import StringIO
import sys

buf = StringIO()

def popen(cmdline):
    return subprocess.Popen(cmdline,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT).stdout

for line in popen('svn info'):
    print >> sys.stdout, 'out: ' + line,
    print >> buf, 'buf: ' + line,

print

print buf.getvalue()
---------------------------------------------------




More information about the Python-list mailing list