Copy Stdout to string

S

sophie_newbie

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!
 
R

Ryan Ginstrom

On Behalf Of sophie_newbie
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...

If I understand you correctly, the following class should work.

from StringIO import StringIO

class OutBuffer(object):
"""Wraps a stream, and keeps output as a buffer

Usage: ['spam', 'egg']
"""

def __init__(self, outstream):
self.out = outstream
self.buffer = StringIO()

def write(self, obj):
"""Writes obj to the output stream, storing it to a buffer as
well"""
self.out.write(obj)
self.buffer.write(obj)

def getvalue(self):
"""Retrieves the buffer value"""
return self.buffer.getvalue()

def __getattr__(self, attr):
"""Delegate everything but write and getvalue to the stream"""
return getattr(self.out, attr)

Regards,
Ryan Ginstrom
 
G

Gerard Flanagan

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()
---------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top