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.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
  • 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 – azro Jan 23 '20 at 22:21
  • One option is to write the output to a [temporary](https://docs.python.org/3/library/tempfile.html) file and read it back into a variable – Anuj Kumar Jan 23 '20 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++? – Jesper Jan 23 '20 at 22:24
  • You could use `StringIO` as suggested in an [answer](https://stackoverflow.com/questions/5884517/python-assign-print-output-to-a-variable). – abc Jan 23 '20 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 – Nicolas Gervais Jan 23 '20 at 22:36

1 Answers1

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91