Often, third-party libraries print information to stdout during execution. While this can be useful for debugging, it can also clutter the output and disrupt other processes. To gain control over this output, consider leveraging a context manager to capture it.
from io import StringIO <br>import sys</p> <p>class Capturing(list):</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">def __enter__(self): self._stdout = sys.stdout sys.stdout = self._stringio = StringIO() return self def __exit__(self, *args): self.extend(self._stringio.getvalue().splitlines()) del self._stringio # free up some memory sys.stdout = self._stdout
To capture output within a specific code block:
<code class="python">with Capturing() as output: do_something(my_object)</code>
After the block, the output variable will contain a list of all the lines printed to stdout.
The above is the detailed content of How to Capture Output from a Python Function with a Context Manager?. For more information, please follow other related articles on the PHP Chinese website!