Reputation: 25
I have a problem with an external library that I use in my script.
I execute a function from this library, but the function prints the output directly. However, I need the output to check if there is a specific string in it.
How can I ensure that the output of the function in the external library comes in a variable so that I can make the comparisons with the string?
Upvotes: 1
Views: 211
Reputation: 89
You can exchange sys.stdout with your buffer temporarily, and then check the buffer.
def external_method():
print ("print something out, don't return")
class MyBuffer(object):
def __init__(self):
self.buffer = []
def write(self, *args, **kwargs):
self.buffer.append(args)
import sys
old_stdout = sys.stdout
sys.stdout = MyBuffer()
external_method()
my_buffer, sys.stdout = sys.stdout, old_stdout
print (my_buffer.buffer)
Upvotes: 1
Reputation: 54263
If you really have no other choice, you could redirect stdout
when you call the library. Here's a piece of code adapted from this answer :
def some_library():
print("Should probably return instead of print.")
import sys
from io import StringIO
class redirected_stdout:
def __init__(self):
self._stdout = None
self._string_io = None
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._string_io = StringIO()
return self
def __exit__(self, type, value, traceback):
sys.stdout = self._stdout
@property
def string(self):
return self._string_io.getvalue()
with redirected_stdout() as out:
some_library()
result = out.string
print("return" in result)
# True
It would be much cleaner to modify the library, though.
Upvotes: 2