简体   繁体   English

python3打印到字符串

[英]python3 print to string

Using Python 3, I have a console application that I am porting to a GUI.使用 Python 3,我有一个要移植到 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.最终使用某些(未定义的)GUI框架呈现每一行。

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.如果我可以将 arguments 转换为 print 通常会产生的字符串,而没有实际打印到 sysout 的副作用,这很容易做到。 In other words, I need a function like this:换句话说,我需要这样的 function:

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?如何将一组参数格式化为 print(...) 生成与 print() 产生的 output 相同的单个字符串?

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.我意识到我可以通过将所有 args 与 sep 和 end 连接起来来模拟 print,但如果有的话,我更愿意使用内置的解决方案。

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.使用打印和重定向 sysout 没有吸引力,因为它需要修改应用程序的全局 state,并且 sysout 可能同时用于其他诊断。

It seems like this should be trivial in Python, so maybe I'm just missing something obvious.看起来这在 Python 中应该是微不足道的,所以也许我只是遗漏了一些明显的东西。

Thanks for any help!谢谢你的帮助!

Found the answer via string io.通过字符串 io 找到答案。 With this I don't have to emulate Print's handling of sep/end or even check for existence.有了这个,我不必模拟 Print 对 sep/end 的处理,甚至不必检查是否存在。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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