Rebinding stdout
Ron Garret
rNOSPAMon at flownet.com
Sun Jan 2 17:02:34 EST 2005
In article <mailman.67.1104698622.22381.python-list at python.org>,
Mark McEahern <marklists at mceahern.com> wrote:
> Ron Garret wrote:
>
> > But this topic does bring up a legitimate question: I have a bunch of
> > code that generates HTML using PRINT statements. I need to convert
> > all this code to return strings rather than actually printing them (so
> > I can use the results to populate templates). In Lisp I could do this:
> >
> > (with-output-to-string (s)
> > (let ( (*standard-output* s) )
> > (call-html-generating-code)
> > s))
> >
> > Is there an equivalent Python trick to capture a function call's
> > output as a string?
> >
> >
> Just to make sure I understand, I'm going to restate your question:
>
> Is there a way to capture stdout?
>
> The answer: Sure, replace it with something file-like:
>
> >>> import sys, StringIO
> >>> default = sys.stdout
> >>> writer = StringIO.StringIO()
> >>> sys.stdout = writer
> >>> print 'Whatever'
> >>> sys.stdout = default
> >>> print writer.getvalue()
> Whatever
>
> >>>
>
> // m
That's exactly what I was looking for. Thanks!
rg
More information about the Python-list
mailing list