python3 print to string
<p>Using Python 3, I have a console application that I am porting to a GUI. The code has a bunch of print statements, something like this:</p>

<p><code>print(' ', 'p', ' ', sep='', end='')</code></p>

<p>(In actuality the positional parameters are actually returns from functions, and there may be more or less than 3, like this:</p>

<p><code>print(f1(), f2(), f3(), sep='', end='')</code></p>

<p>I would like to convert these calls into something like:</p>

<p><code>GuiPrintLine(' ', 'p', ' ', sep='', end='')</code></p>

<p>where each line is eventually rendered using the GUI framework.</p>

<p>This is easy to do if I can convert the arguments to a string.  I'd like to format the parameter list as a single string that print would normally output with something like this:</p>

<pre><code>def GuiPrintLine(*args, **kwargs):
    s = text.format(*args, **kwargs)
    # ... then display the string on the gui ...
</code></pre>

<p>However this requires a format string (text).  Is there a simple way to do this that automatically produces the same output as the print function?  I realize I could emulate print by concatinating all the args with sep and ends, but I would prefer to use a built-in solution if there is one. </p>

<p>using print and redirecting sysout is not attractive since it requires modifying the global state of the app and sysout might be used for other diagnostics at the same time.</p>

<p>It seems like this should be trivial in Python, so maybe I'm just missing something obvious.</p>

<p>Thanks for any help!</p>

<p>Found the answer via string io.  With this I don't have to emulate Print's handling of sep/end or even check for existence.</p>

<pre><code>import io

def print_to_string(*args, **kwargs):
    output = io.StringIO()
    print(*args, file=output, **kwargs)
    contents = output.getvalue()
    output.close()
    return contents
</code></pre>

python string python-3.x stringio