我有一个打印功能。如何将其输出为字符串?
注意:我无法更改功能代码。
def f():
print('hello world')
# do something
assert x == 'hello world\n'
我需要这个,因为火花数据框中有方法explain
即打印约执行计划的信息。但我需要这个信息作为我的程序中的字符串。
>>> df.explain()
== Physical Plan ==
Scan ExistingRDD[age#0,name#1]
我在这里找到了解决方案https://stackoverflow.com/a/22434594/4204843
def f():
print('hello world')
import io
from contextlib import redirect_stdout
with io.StringIO() as buf, redirect_stdout(buf):
f()
x = buf.getvalue()
assert x == 'hello world\n'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句