Capturing Standard Output from Python Function Calls
When using Python libraries that modify objects and print statistics to stdout, there may be a need to capture this output for further analysis. However, directly modifying the function to return such information might not always be feasible.
To address this, one can utilize the Capturing context manager:
<code class="python">from io import StringIO import sys class Capturing(list): 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</code>
The Capturing context manager can be used as follows:
<code class="python">with Capturing() as output: do_something(my_object)</code>
After the function call, the output list will contain the lines printed by the function.
This technique can be applied multiple times, and the results can be concatenated:
<code class="python">with Capturing() as output: print('hello world') print('displays on screen') with Capturing(output) as output: # note the constructor argument print('hello world2') print('done') print('output:', output)</code>
Output:
displays on screen done output: ['hello world', 'hello world2']
This approach provides an effective workaround for capturing stdout output when it is not possible to modify the do_something() function directly.
The above is the detailed content of How to Capture Standard Output from Python Function Calls?. For more information, please follow other related articles on the PHP Chinese website!