简体   繁体   中英

python3 print to string

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!

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

My solution:

def print_to_string(*args, **kwargs):
    newstr = ""
    for a in args:
        newstr+=str(a)+' '
    return newstr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM