Nicolas Gervais
Nicolas Gervais

Reputation: 36624

Save the content of the print statement in Python

I'm using someone's code in c++ which is called by python. I have no way of getting into the source code and modify it. When called with python, it prints something, and I want to assign this output to a variable. How can I do that?

def print_something(string):
    print(string)

x = print_something('foo')
print(type(x))
Out[5]: NoneType

Ideally, this code would assign 'foo' to x as a string.

Upvotes: 1

Views: 1419

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195468

Maybe you can redirect sys.stdout to buffer?

import sys
from io import StringIO

stdout_backup = sys.stdout
sys.stdout = string_buffer = StringIO()

# this function prints something and I cannot change it:
def my_function():
    print('Hello World')

my_function()  # <-- call the function, sys.stdout is redirected now

sys.stdout = stdout_backup  # restore old sys.stdout

string_buffer.seek(0)
print('The output was:', string_buffer.read())

Prints:

The output was: Hello World

Upvotes: 5

Related Questions