1

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.

5
  • If you can't touch the code of the method, you can't change its behaviour so you can't ask to get back something that is not returned yet Commented Jan 23, 2020 at 22:21
  • One option is to write the output to a temporary file and read it back into a variable Commented Jan 23, 2020 at 22:22
  • How do you actually call the C++ code? It doesn't show from the Python code you listed. print() is a built-in function in (recent) Python, but you seem to say that print() calls someone else's code written in C++? Commented Jan 23, 2020 at 22:24
  • You could use StringIO as suggested in an answer. Commented Jan 23, 2020 at 22:25
  • I call it from the cmd. In turn, it uses dll files and so on. Can't really give you more details unfortunately Commented Jan 23, 2020 at 22:36

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Or even an open file handle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.