python3 print to string

Question:

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:

print(f1(), f2(), f3(), sep=getsep(), end=getend())

I would like to convert these calls into something like:

GuiPrintLine(f1(), f2(), f3(), sep=getsep(), end=getend())

where each line is eventually rendered using some (undefined) GUI framework.

This is easy to do if I can convert the arguments to print into to the string that print would normally produce without the side-effect of actually printing to sysout. In other words, I need a function like this:

s = print_to_string(*args, **kwargs)

How do I format a set of parameters to print(…) into a single string that produces the same output as print() would produce?

I realize I could emulate print by concatenating all the args with sep and ends, but I would prefer to use a built-in solution if there is one.

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.

It seems like this should be trivial in Python, so maybe I’m just missing something obvious.

Thanks for any help!

Asked By: Brad

||

Answers:

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.

import io

def print_to_string(*args, **kwargs):
    output = io.StringIO()
    print(*args, file=output, **kwargs)
    contents = output.getvalue()
    output.close()
    return contents
Answered By: Brad

My solution :

def print_to_string(*args, **kwargs):
    newstr = ""
    for a in args:
        newstr+=str(a)+' '
    return newstr
Answered By: Géo-IT Solutions
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.