I have a Python script that is using some closed-box Python functions (i.e. I can\'t edit these functions) provided by my employer. When I call these functions, they are pri
Not really requested by the OP, but I needed to hide and store the output, and did like follows:
from io import StringIO
import sys
class Hider:
def __init__(self, channels=('stdout',)):
self._stomach = StringIO()
self._orig = {ch : None for ch in channels}
def __enter__(self):
for ch in self._orig:
self._orig[ch] = getattr(sys, ch)
setattr(sys, ch, self)
return self
def write(self, string):
self._stomach.write(string)
def flush(self):
pass
def autopsy(self):
return self._stomach.getvalue()
def __exit__(self, *args):
for ch in self._orig:
setattr(sys, ch, self._orig[ch])
Usage:
with Hider() as h:
spammy_function()
result = h.autopsy()
(tested only with Python 3)
EDIT: now allows to select stderr, stdout or both, as in Hider([stdout, stderr])