2 回答
TA贡献1799条经验 获得超8个赞
您可以暂时将 sys.stdout 与您的缓冲区交换,然后检查缓冲区。
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)
TA贡献1797条经验 获得超6个赞
如果你真的别无选择,你可以stdout在调用库时重定向。这是改编自此答案的一段代码:
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
不过,修改库会更干净。
添加回答
举报