0

I have a function that prints. How to get its output to string?
Note: I cant change the function code.

def f():
    print('hello world')

# do something

assert x == 'hello world\n'

I need this because spark dataframe has method explain that prints info about execution plan. But I need this info as string in my program.

>>> df.explain()
== Physical Plan ==
Scan ExistingRDD[age#0,name#1]
zero323
  • 305,283
  • 89
  • 921
  • 912
tandav
  • 759
  • 2
  • 8
  • 12

1 Answers1

0

I found solution here 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'
tandav
  • 759
  • 2
  • 8
  • 12